sed:在添加之前测试$ line中的$ pattern
问题描述:
有几个示例说明如何使用sed基于匹配一般模式将文本添加到行尾。 Here's one example。
在这个例子中,海报
somestuff...
all: thing otherthing
some other stuff
开始,并希望增加的all:
结束,就像这样:
somestuff...
all: thing otherthing anotherthing
some other stuff
一切都很好。但是,如果anotherthing
已经存在,会发生什么?!
我想找到以all:
行,测试的anotherthing
,并只存在添加它,如果它是从线丢失。
我该怎么做?
我的具体情况正在测试中grub.conf
kernel
线的boot=
和fips=1
的存在,并加入一个或两个的这些参数只有他们不是已经在该行。 (我想搜索/添加要idempotent。)
答
这可能为你工作(GNU SED):
sed '/^all:/!b;/anotherthing/!s/$/ anotherthing/' file
Disrequard任何行不all:
,只有不包含anotherthing
替代线开始。
答
您可以使用此awk
检查给定字符串的存在和它附加只有当它不存在:
awk -v s='anotherthing' '/^all:/ && $0 !~ s "$" { $0 = $0 OFS s } 1' file
答
跳过线,anotherthing,并把它添加到剩余的行开始all:
sed '/anotherthing/!s/^all:.*$/& anotherthing/' file