bash - sed:在添加之前测试 $line 中的 $pattern

标签 bash sed redhat

有几个示例说明如何使用 sed 根据匹配的通用模式将文本添加到行尾。 Here's one example .

在该示例中,海报开头为

somestuff...
all: thing otherthing
some other stuff

并且想要添加到 all: 的末尾,如下所示:

somestuff...
all: thing otherthing anotherthing
some other stuff

一切都很好。但是,如果另一个已经存在会发生什么?!

我想找到以 all: 开头的行,测试是否存在 anotherthingonly 如果行中缺少该内容,请添加它。

我该怎么做?

我的具体案例是测试 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/

相关文章:

bash - 通过 ID 在文本中查找单词并替换同一行中的其他单词

php - bash 脚本从命令行运行,但不是从 cron 运行

linux - 通过 bash 中的第一个字母从一个数组创建新数组

sed - sed 和 awk 有什么区别?

linux - 为什么 sed 将此替换的结果评估为 8?

linux - 查询最近卸载的rpm包

mysql无法建立远程连接

linux - 如何在 linux redhat 中列出池?

regex - 删除两个方向的n行和sed中的匹配?

bash - 需要使用 shell 脚本从文件中替换行的特定部分