Sed

sed 命令成功地在文件中查找和替換,位擦除新文件中的所有內容

  • August 2, 2021

我在名為 test2.txt 的文件中有這個 xml 文本

<This is a line of text with a year=2020 month=12 in it
This line of text does not have a year or month in it
This year=2021 is the current year the current month=1
This is the year=2021 the month=2/>


<This is a line of text with a year=33020 month=12 in it
This line of text does not have a year or month in it
This year=33020 is the current year the current month=1
This is the year=33020 the month=2/>

我在文件上執行這個正則表達式:我喜歡commnet第一段,但保留文件的其餘部分

sed -i -En '/./{H;$!d} ; x ; s/<(This.*2020.*)\/>/<!--\1-->/p' test2.txt

但結果是 sed 命令刪除了文件中所有其餘的字元串並將正則表達式 init 的結果放入,所以現在 test2.txt 看起來像這樣:

<!--This is a line of text with a year=2020 month=12 in it
This line of text does not have a year or month in it
This year=2021 is the current year the current month=1
This is the year=2021 the month=2-->

如何執行正則表達式但將其他文本保留在文件中?

您明確告訴 sed不要列印,除非該行與模式匹配。因此,只需刪除運算符之後的the-n和 the ,它就會按您的預期工作:p``s///

$ sed  -E '/./{H;$!d} ; x ; s/<(This.*2020.*)\/>/<!--\1-->/'  file

<!--This is a line of text with a year=2020 month=12 in it
This line of text does not have a year or month in it
This year=2021 is the current year the current month=1
This is the year=2021 the month=2-->


<This is a line of text with a year=33020 month=12 in it
This line of text does not have a year or month in it
This year=33020 is the current year the current month=1
This is the year=33020 the month=2/>

但是,這仍然會在開頭添加一個額外的換行符。幸運的是,@Philippos告訴我如何解決這個問題,所以請改用它:

$ sed -E '/./{H;1h;$!d} ; x ; s/<(This.*2020.*)\/>/<!--\1-->/'  file
<!--This is a line of text with a year=2020 month=12 in it
This line of text does not have a year or month in it
This year=2021 is the current year the current month=1
This is the year=2021 the month=2-->


<This is a line of text with a year=33020 month=12 in it
This line of text does not have a year or month in it
This year=33020 is the current year the current month=1
This is the year=33020 the month=2/>

或者,要編輯原始文件:

sed -i.bak -E '/./{H;1h;$!d} ; x ; s/<(This.*2020.*)\/>/<!--\1-->/'  file

引用自:https://unix.stackexchange.com/questions/662974