0

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
3
  • Does it have to be sed? It's easier with awk. Commented Feb 13, 2014 at 9:28
  • Yes. It has to be sed. Commented Feb 13, 2014 at 9:30
  • your result is containting an a2 b2 that normally does not. Commented Feb 13, 2014 at 10:41

3 Answers 3

1

This might work for you (GNU sed):

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

or:

sed '/\<a2\>/!b;/\<b2\>/!d' file
Sign up to request clarification or add additional context in comments.

3 Comments

@OlegG are you using GNU sed? If not try sed -e '/\<a2\>/!b' -e '/\<b2\>/!d' file
But I used without that /</>. It was enough just sed -e "/a2/!b" -e "/b2/!d" file
@OlegG I don't think you will get the correct values if you remove the start/end word boundary anchors.
1

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.

8 Comments

sed miss if b2 is before a2 or b2 is not followed by a char but work on given sample, so +1
@NeronLeVelu updated my answer since it was way to wide and will not work for a2 c2that should be deleted. awk is the east way to go.
Guys, sed is required
@OlegG I do know, but it does not hurt any body posting other solution. sed 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?
@Jotne I don't have a problem to solve this in awk. I want to use sed's -i option to avoid one line of code.
|
1
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'

1 Comment

On Ubuntu, I do get this error -bash: !{p: event not found

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.