簡體   English   中英

如何使用sed命令從文件中刪除包含特定字符串的行

[英]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.

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