sed - 删除包含一个模式但不包含另一个模式的所有行

时间:2015-01-01 20:37:54

标签: bash sed

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

例如,如果我有这个文件:

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

6 个答案:

答案 0 :(得分:4)

这应该有效

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

答案 1 :(得分:4)

awk替代方案:

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

答案 2 :(得分:4)

单个sed调用:

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

对于匹配/hello/的行,如果它也匹配/world/删除,则打印

答案 3 :(得分:1)

只需使用awk保持逻辑简单如下:

$ awk '/hello/ && !/world/{next} 1' file
hello world bar
blah blah blah

答案 4 :(得分:0)

sed -i.bak '/hello/{/world/!d}

这个答案是不同的,因为向-i提供了扩展。

我下面的帖子应该是有用的

sed command with -i option failing on Mac, but works on Linux

答案 5 :(得分:0)

在玩了一下之后,我能够获得一个实现sed的脚本,这对我有用:

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