[英]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.