简体   繁体   中英

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

I want to delete all lines in a file that contain one pattern, but not another.

For example, if I have this file:

hello people foo
hello world bar
hello something
blah blah blah

I want to delete all lines that contain hello , but not world , so that my file looks like this:

hello world bar
blah blah blah

I tried the following:

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

But I get the error message -i may not be used with stdin

这应该工作

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

一个awk的替代品:

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

A single sed invocation:

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

For lines matching /hello/ , if it also matches /world/ delete, else print

Just use awk to keep the logic simply as-stated:

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

this answer is different since an extension is provided to -i.

I the thread below should be useful

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

After playing a round a bit, I was able to procure one script implementing sed , which worked for me:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM