在使用sed找到匹配项后,是否有方法替换以下两行?
我有文件
#ABC
oneSize=bar
twoSize=bar
threeSize=foo
但我想在模式#ABC
匹配后,替换两条直接线,使其成为
#ABC
oneSize=foo
twoSize=foo
threeSize=foo
我能做到
但它只改变了第twoSize
行,而不是第oneSize
行
有没有办法让它同时改变单码和双码
在使用sed找到匹配项后,是否有方法替换以下两行?
我有文件
#ABC
oneSize=bar
twoSize=bar
threeSize=foo
但我想在模式#ABC
匹配后,替换两条直接线,使其成为
#ABC
oneSize=foo
twoSize=foo
threeSize=foo
我能做到
但它只改变了第twoSize
行,而不是第oneSize
行
有没有办法让它同时改变单码和双码
gnu和其他一些sed版本允许您使用相对数获取范围,因此您可以简单地使用:
sed -E '/^#ABC$/,+2 s/(Size=)bar/\1foo/' file
#ABC
oneSize=foo
twoSize=foo
threeSize=foo
Command details:
/^#ABC$/,+2
个匹配范围从模式#ABC
到下两行s/(Size=)bar/\1foo/
:匹配Size=bar
并替换为Size=foo
,使用捕获组避免在搜索和替换中重复相同的字符串您还可以考虑awk
,以避免重复模式和替换N次,如果你必须在匹配模式之后替换N行:
awk 'n-- {sub(/Size=bar/, "Size=foo")} /^#ABC$/ {n=2} 1' file
#ABC
oneSize=foo
twoSize=foo
threeSize=foo