簡體   English   中英

替換所有不包含匹配字符串的行

[英]Replace All Lines That Do Not Contain Matched String

我正在處理這個看起來像這樣的數據文件:

text in file
hello random text in file
example text in file
words in file hello
more words in file
hello text in file can be
more text in file

我正在嘗試使用 sed 用match替換所有包含字符串hello ,因此輸出將是:

match
hello random text in file
match
words in file hello
match
hello text in file can be
match

我嘗試使用sed '/hello/!d'但這會刪除該行。 另外,我讀到我可以匹配使用! 在 sed 中,但我不確定如何匹配每一行並正確替換。 如果您能給我一些指導,我將不勝感激。

你可以這樣做:

$ sed '/hello/!s/.*/match/' infile
match
hello random text in file
match
words in file hello
match
hello text in file can be
match

/hello/! 確保我們只替換不包含hello (你說得對),然后替換用match替換完整的模式空間( .* )。

awk來救援!

$ awk '!/hello/{$0="match"}1' file

用“match”替換與“hello”不匹配的行並打印所有行。

使用c (更改)命令 sed:

$ sed '/hello/!c match' file
match
hello random text in file
match
words in file hello
match
hello text in file can be
match

為了清晰、簡單等目的,只需使用 awk:

awk '{print (/hello/ ? $0 : "match")}' file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM