簡體   English   中英

sed-刪除所有包含一種模式但不包含另一種模式的行

[英]sed - delete all lines that contain one pattern but not another

我想刪除文件中包含一種模式但不包含另一種模式的所有行。

例如,如果我有此文件:

hello people foo
hello world bar
hello something
blah blah blah

我想刪除所有包含hello而不是world ,以便我的文件如下所示:

hello world bar
blah blah blah

我嘗試了以下方法:

sed -n '/hello/p' file | sed -i '/world/!d'

但是我收到錯誤消息-i may not be used with stdin

這應該工作

sed  -i '/hello/{/world/!d}' file

一個awk的替代品:

awk '!/hello/ ||/world/' file

單個sed調用:

sed -n '/hello/ {/world/d; p}' file

對於與/hello/匹配的行,如果它也與/world/匹配,則刪除,否則打印

只需使用awk即可簡單地保持邏輯狀態:

$ awk '/hello/ && !/world/{next} 1' file
hello world bar
blah blah blah
sed -i.bak '/hello/{/world/!d}

由於對-i提供了擴展名,因此此答案有所不同。

我下面的線程應該有用

帶有-i選項的sed命令在Mac上失敗,但在Linux上工作

經過一輪回合,我能夠獲得一個實現sed腳本,該腳本對我sed

file=$1
patt=$(sed -n '/world/p' $file)
sed -n "/hello/!p;/$patt/p" $file

暫無
暫無

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

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