如何在与 Sed 匹配后替换连续的 2 行

How to replace 2 consecutive lines after Match with Sed

有没有办法在使用 sed 找到匹配项后替换以下两行?

我有一个文件

#ABC
oneSize=bar
twoSize=bar
threeSize=foo

但是我想在模式 #ABC 匹配后替换直接的两行,以便它变成

#ABC
oneSize=foo
twoSize=foo
threeSize=foo

我能做到 gsed '/^#ABC/{n;s/Size=bar/Size=foo/}' file

但它只改变行 twoSize 而不是 oneSize

有没有办法让它同时改变 oneSize 和 twoSize

您可以重复命令:

gsed '/^#ABC/{n;s/Size=bar/Size=foo/;n;s/Size=bar/Size=foo/}' file

参见online demo

n command "打印模式space,然后,无论如何,将模式space替换为下一行输入。如果没有更多输入然后 sed 退出而不处理任何更多命令。"

因此,第一次使用它时,在以 #ABC 开头的行之后的第一行进行替换,然后在该行下方的第二行进行替换。

gnu 和其他一些 sed 版本允许您使用相对数获取范围,因此您可以简单地使用:

sed -E '/^#ABC$/,+2 s/(Size=)bar/foo/' file
#ABC
oneSize=foo
twoSize=foo
threeSize=foo

命令详情:

  • /^#ABC$/,+2 匹配范围从模式 #ABC 到下两行
  • s/(Size=)bar/foo/:匹配Size=bar并替换为Size=foo,使用捕获组避免在搜索和替换中重复相同的字符串

如果在匹配模式后必须替换 N 行,您也可以考虑 awk 以避免重复模式和替换 N 次:

awk 'n-- {sub(/Size=bar/, "Size=foo")} /^#ABC$/ {n=2} 1' file

#ABC
oneSize=foo
twoSize=foo
threeSize=foo

使用 sed,当不再找到 Size=bar 时循环将中断,因此替换匹配后的前两行。

$ sed '/^#ABC/{:l;n;s/Size=bar/Size=foo/;tl}' input_file
#ABC
oneSize=foo
twoSize=foo
threeSize=foo

使用 sed -z

sed -z 's/#ABC\noneSize=bar\ntwoSize=bar/#ABC\noneSize=foo\ntwoSize=foo/' file.txt
#ABC
oneSize=foo
twoSize=foo
threeSize=foo

或者

sed -E -z 's/#ABC\n(.*)bar\n(.*)bar/#ABC\nfoo\nfoo/' file.txt