有几个示例说明如何使用 sed 根据匹配的通用模式将文本添加到行尾。 Here's one example .
在该示例中,海报开头为
somestuff...
all: thing otherthing
some other stuff
并且想要添加到 all:
的末尾,如下所示:
somestuff...
all: thing otherthing anotherthing
some other stuff
一切都很好。但是,如果另一个
已经存在会发生什么?!
我想找到以 all:
开头的行,测试是否存在 anotherthing
和 only 如果行中缺少该内容,请添加它。
我该怎么做?
我的具体案例是测试 grub.conf
中的 kernel
行是否存在 boot=
和 fips=1
,并添加其中一个或两个参数仅当它们尚未在行中。 (我希望搜索/添加为 idempotent 。)
最佳答案
跳过包含其他内容的行并将其添加到以 all:
开头的剩余行
sed '/anotherthing/!s/^all:.*$/& anotherthing/' file
关于bash - sed:在添加之前测试 $line 中的 $pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42542577/