繁体   English   中英

如何在与 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

请参阅在线演示

n命令打印模式空间,然后无论如何用下一行输入替换模式空间。如果没有更多输入,则 sed 退出而不处理任何更多命令。

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

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

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

命令详细信息:

  • /^#ABC$/,+2从模式#ABC到下两行的匹配范围
  • s/(Size=)bar/\1foo/ :匹配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\n\1foo\n\2foo/' file.txt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM