![](/img/trans.png)
[英]sed: How to match these 4 consecutive lines with RegEx for deleting?
[英]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
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.