Operating System - HP-UX
1753861 Members
7338 Online
108809 Solutions
New Discussion юеВ

grep "abc" but exclude "def" and "ghi" in the file

 
Hanry Zhou
Super Advisor

grep "abc" but exclude "def" and "ghi" in the file

by using one grep statement.

Can I do that?
none
7 REPLIES 7
A. Clay Stephenson
Acclaimed Contributor

Re: grep "abc" but exclude "def" and "ghi" in the file

Multiple patterns using -e's with grep are logical OR's (or logical AND's if combined with -v) so that if any pattern matches the line is output. Thus the answer is no but you could:

grep -e 'abc' < infile | grep -v -e 'def' -e 'ghi' > outfile
If it ain't broke, I can fix that.
Suresh Patoria
Super Advisor

Re: grep "abc" but exclude "def" and "ghi" in the file

Hi

Use the command

grep "abc" -v "def" "ghi" <>

Thanx
Elmar P. Kolkman
Honored Contributor

Re: grep "abc" but exclude "def" and "ghi" in the file

Not grep, but tools like awk could be very handy:
awk '/def/ {next} /ghi/ {next} /abc/'
should do the trick.
Every problem has at least one solution. Only some solutions are harder to find.
Michael Schulte zur Sur
Honored Contributor

Re: grep "abc" but exclude "def" and "ghi" in the file

Hi,

Clays├В┬┤s and Elmar├В┬┤s work.
Suresh: it doesnt work that way. You cant include and exclude with multiple patterns at the same time.

greetings,

Mich
Hanry Zhou
Super Advisor

Re: grep "abc" but exclude "def" and "ghi" in the file

Elmart,

What is '{next}' in awk, can you please explain it to me?

Thanks,
none
Michael Schulte zur Sur
Honored Contributor

Re: grep "abc" but exclude "def" and "ghi" in the file

Hi,

next tells awk to discard this line and start the loop with the next line.

greetings,

Michael
Michael Schulte zur Sur
Honored Contributor

Re: grep "abc" but exclude "def" and "ghi" in the file

Hi,

if the problem is solved, could you spare some points from the endless supply of points, HP has, for those, who could help you? ;-)

greetings,

Michael