[英]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
腳本,該腳本對我sed
:
file=$1
patt=$(sed -n '/world/p' $file)
sed -n "/hello/!p;/$patt/p" $file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.