繁体   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