OlegG
OlegG

Reputation: 1017

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. I.e. to get the following result:

a1 b1
a2 b2
a3 b3
a4 b4

Upvotes: 0

Views: 89

Answers (3)

NeronLeVelu
NeronLeVelu

Reputation: 10039

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'

Upvotes: 1

potong
potong

Reputation: 58578

This might work for you (GNU sed):

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

or:

sed '/\<a2\>/!b;/\<b2\>/!d' file

Upvotes: 1

Jotne
Jotne

Reputation: 41460

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.

Upvotes: 1

Related Questions