簡體   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