簡體   English   中英

sed / awk:刪除所有與一個單詞匹配的行,而不是另一個

[英]sed / awk: Delete all lines matching a word not followed by another word

我的文件中包含以下幾行。

<stuff>
test1.*test2
test1
test1.*test2
test1
<other stuff>

我想刪除所有包含test1的行,但不刪除test2 -這意味着我應該以:

<stuff>
test1.*test2
test1.*test2
<other stuff>

我已經嘗試了很多正則表達式,但似乎無法破解sed或awk。 這是我在用vim regexp測試之后的最新嘗試。

sed -i .bk '/^.*test1\(\(test2\)\@!.\)*$/d' file

(這是Mac OS X上bash腳本的一部分)

使用兩個表達式。 第一個跳過test1后跟test2 ,第二個刪除test1僅在不存在test2下才可以到達它。

sed -e '/test1.*test2/b' -e '/test1/d'

嘗試類似的方法:

awk '/test1/&&!/test2/{next}1' file

我們告訴awk:

  • test1查找行。
  • 在同一行上, test2不應該存在
  • 如果找到這樣的行,我們跳過
  • 如果找不到這樣的行,我們打印

$ cat file
<stuff>
test1.*test2
test1
test1.*test2
test1
<other stuff>

$ awk '/test1/&&!/test2/{next}1' file
<stuff>
test1.*test2
test1.*test2
<other stuff>

帶有perl正則表達式的GNU grep:

grep -vP 'test1(?!.*test2)' file
$ awk '!/test1/||/test2/' file
<stuff>
test1.*test2
test1.*test2
<other stuff>

暫無
暫無

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

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