有沒有辦法在使用 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
uj5u.com熱心網友回復:
您可以重復以下命令:
gsed '/^#ABC/{n;s/Size=bar/Size=foo/;n;s/Size=bar/Size=foo/}' file
請參閱在線演示。
n命令“列印模式空間,然后無論如何,用下一行輸入替換模式空間。如果沒有更多輸入,則 sed 退出而不處理任何更多命令。 ”
因此,第一次使用它時,您在以 開頭的行之后的第一行#ABC替換,然后在該行下面的第二行替換。
uj5u.com熱心網友回復:
gnu 和其他一些 sed 版本允許您使用相對數字來獲取范圍,因此您可以簡單地使用:
sed -E '/^#ABC$/, 2 s/(Size=)bar/\1foo/' file
#ABC
oneSize=foo
twoSize=foo
threeSize=foo
命令詳情:
/^#ABC$/, 2匹配范圍從模式#ABC到下 2 行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
uj5u.com熱心網友回復:
使用sed,當Size=bar不再找到時回圈將中斷,因此替換匹配后的前 2 行。
$ sed '/^#ABC/{:l;n;s/Size=bar/Size=foo/;tl}' input_file
#ABC
oneSize=foo
twoSize=foo
threeSize=foo
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/455235.html
下一篇:陣列中的Bash關聯陣列
