sed 在包含多個無序字串的行之後追加

sed 在包含多個無序字串的行之後追加

我正在嘗試使用 sed 在包含和appendstring的行之後追加。HelloWorld

Hello something here World
World fsf Hello

如果我確實考慮順序,這會起作用:

sed -i '/Hello*World\|World*Hello/a appendstring' file

但是如果我有很多字串要匹配並且它們不按順序排列,那麼這肯定是無效的。

然後我嘗試了另一個連結中的解決方案,該連結討論刪除包含兩個字串的行而不考慮它們的順序。

https://stackoverflow.com/questions/28561519/delete-lines-that-ontain-two-strings

然而,

sed -i '/Hello/!b;/World/d' file

這甚至不適用於刪除。

以下內容,也是該問題的答案之一:

sed -i '/Hello/{/World/d}' file

作品,所以我嘗試將其實現為追加。使用:

sed -i '/Hello/{/World/a} appendstring' file

但收到錯誤:

sed: -e expression #1, char 0: unmatched `{'

更新: 連結中的帖子用 !b 說明了解決方案,由於感嘆號,它在 cshell 中不起作用,但它在 sh 和 bash 中起作用。而且它還可以輕鬆擴展為在腳本內運行 sed 時插入多行以及附加大段落。

sed -i '/Hello/!b; /World/a \
addline \
addanotherline ' file

答案1

你幾乎已經受夠了:

sed -i '/Hello/{/World/a} appendstring' file

你需要分開你的論點。使用-e,像這樣:

sed -i -e '/Hello/{/World/a appendstring' -e '}' file

請注意,使用A不帶換行符的 pend 指令是 GNU 擴展,-i開關也是如此。


為了更方便地做到這一點,並考慮多個字串匹配的可能性,請嘗試:

sed '/multiple/{/words/{/to/{/match/ s/$/append this/;};};}' file > newfile
mv newfile file

由於您已經在使用 GNU Sed,因此只需使用:

sed -i -e '/multiple/{/words/{/to/{/match/ a append this' -e 'a and also this' -e 'a oh and this too' -e '};};}' file

相關內容