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
This might work for you (GNU sed):
sed '/\ba2\b/!b;/\bb2\b/!d' file
or:
sed '/\<a2\>/!b;/\<b2\>/!d' file
sed -e '/\<a2\>/!b' -e '/\<b2\>/!d' filesed -e "/a2/!b" -e "/b2/!d" fileUsing 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.
a2 c2that should be deleted. awk is the east way to go.sed is requiredsed may not always be the best tool, and if you have sed there are big possibility that you also have awk. You do not have awk?awk. I want to use sed's -i option to avoid one line of code.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'
-bash: !{p: event not found
sed? It's easier withawk.sed.