sed:在添加 $line 之前测试 $pattern
sed: test for $pattern in $line before adding it
有几个示例说明如何使用 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
,并添加其中一个或两个参数 只有当 他们还没有在队列中时。 (我希望 search/add 为 idempotent。)
这可能对你有用 (GNU sed):
sed '/^all:/!b;/anotherthing/!s/$/ anotherthing/' file
忽略不以 all:
开头的任何行,仅替换不包含 anotherthing
.
的行
您可以使用此 awk
检查给定字符串是否存在并仅在不存在时附加它:
awk -v s='anotherthing' '/^all:/ && [=10=] !~ s "$" { [=10=] = [=10=] OFS s } 1' file
跳过另一行并将其添加到以 all:
开头的剩余行
sed '/anotherthing/!s/^all:.*$/& anotherthing/' file
有几个示例说明如何使用 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
,并添加其中一个或两个参数 只有当 他们还没有在队列中时。 (我希望 search/add 为 idempotent。)
这可能对你有用 (GNU sed):
sed '/^all:/!b;/anotherthing/!s/$/ anotherthing/' file
忽略不以 all:
开头的任何行,仅替换不包含 anotherthing
.
您可以使用此 awk
检查给定字符串是否存在并仅在不存在时附加它:
awk -v s='anotherthing' '/^all:/ && [=10=] !~ s "$" { [=10=] = [=10=] OFS s } 1' file
跳过另一行并将其添加到以 all:
sed '/anotherthing/!s/^all:.*$/& anotherthing/' file