gpt4 book ai didi

sed 查找字符串,打印所有内容直到下一个模式

转载 作者:行者123 更新时间:2023-12-01 23:44:07 25 4
gpt4 key购买 nike

我们继承了以下场景。

带有“每个服务的主机数”的文件通过管道传输到 sed。

将根据服务名称返回主机列表。

使用的命令:

/bin/sh -c 'cat file.txt | sed -n "/main-service]/,/\\[/{/\\[/!p;}"'

操作系统:Ubuntu 14 16 18 20

在路上我们发现 sed 返回的主机数量超出了我们的预期。

我试图在不修改 sed 的第一部分('/main-service]/')的情况下修复这种“贪婪”行为,

对此的修复可以是:'/\[main-service]/',但我不知道它到底能阻止什么(这个 sed 在很多地方使用),所以我试图避免这种编辑。

文件示例(Sed 输入):

[main-service]
hosta
hostb
hostc

[that-main-service]
hostd
hoste


[other-main-service]
hostf
hostg

在下面的示例中,我们正在寻找“main-service”下的所有主机

/bin/sh -c 'cat file.txt | sed -n "/main-service]/,/\\[/{/\\[/!p;}"'

然而,输出不是我们期望的输出

hosta
hostb
hostc

hostf
hostg

我不知道创建者对 sed 语法的确切含义,但我想要实现的是:

if service name == '/main-service]/' #find only the line that matches

take all the text until '\n\['

这里的例子:

https://sed.js.org/?gist=0a90e4d015d02b820072e6cf837e6204

预期的输出是:

hosta
hostb
hostc

如有任何帮助,我们将不胜感激。

谢谢。

最佳答案

根据您展示的示例,您能否尝试在 awk 中执行以下操作。

awk '/^\[/ && found{exit} /^\[main-service\]/{found=1;next} found && NF' Input_file

输出如下。

hosta
hostb
hostc

说明: 为以上添加详细说明。

awk '                 ##Starting awk program from here.
/^\[/ && found{ ##Checking condition if line starts from [ and found is NOT NULL then do following.
exit ##exit from this program, no need to read whole Input_file.
}
/^\[main-service\]/{ ##Checking condition if line starts from [ main-service] then do following.
found=1 ##Setting found to 1 here.
next ##next will skip all further statements from here.
}
found && NF ##Checking condition if found is SET and NF is NOT NULL then print that line.
' Input_file ##Mentioning Input_file name here.

关于sed 查找字符串,打印所有内容直到下一个模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64523602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com