[英]How to remove a line containing specific string from file with sed command
我有以下文件:
#!example
#!toto
example
#example
;example
toto
example
我想刪除包含字符串"example"
的行,除了行以"#!"
開頭 。
所以結果文件應該是:
#!example
#!toto
toto
如何只sed
命令呢?
這條線怎么樣:
sed '/^#!/n;/example/d' file
使用示例文本進行測試:
kent$ cat file
#!example
#!toto
example
#example
;example
toto
example
kent$ sed '/^#!/n;/example/d' file
#!example
#!toto
toto
如果你願意, awk也可以這樣做:
kent$ awk '/^#!/ || !/example/' file
#!example
#!toto
toto
編輯
SED:
starting with #!
,停止處理,轉到下一行( n
) #!
檢查是否含有example
,如果是的話, d
刪除(不輸出打印) AWK
#!
開始#!
或( ||
)不包含示例。 性能:
我不能說。 因為要求很簡單。 您可以構建一個巨大的文件,並使用time
自己進行比較。
如果你想只保留以#!
開頭的行#!
$ sed '/#!/!d' foo.sh
#!example
#!toto
這可能適合你(GNU sed):
sed '/#!/b;/example/d' file
這會打印包含#!
所有行#!
以及包含example
所有其他行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.