简体   繁体   中英

SED: delete lines containing first pattern and not containing second pattern

I have a file content like that:

a1 b1
a2 b2
a2 b21
a2 b22
a3 b3
a4 b4

I need delete with sed lines which contain a2 and not contain b2. Ie to get the following result:

a1 b1
a2 b2
a3 b3
a4 b4

Using awk you can do:

cat file
a1 b1
a2 b2
a2 b21
a2 b22
a3 b3
a4 b4
a2 c3

awk '$1=="a2" && $2!="b2" {next} 8'
a1 b1
a2 b2
a3 b3
a4 b4

If field #1 is a2 and filed #2 is not b2 skip the line.

sed -n --posix -e '/a2/ !{
   p
   b
   }
/b2/ !p'

(adapted based on remark of Jotne + correction b instead of t ) print if not containing a2 then go to next line, if containt, print if not containing b2

or smaller

sed -n '/a2/ {/b2/ b
   }
p'

This might work for you (GNU sed):

sed '/\ba2\b/!b;/\bb2\b/!d' file 

or:

sed '/\<a2\>/!b;/\<b2\>/!d' 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