Tree
Tree

Reputation: 10362

How to use 'grep' to match a string except when another string matches?

In the following file I just looking for a grep command:

Line 1 : string 1  (errno:1)
Line 2 : string 1  (errno:3)
Line 3 : string 1  (errno:1)
Line 4 : string 1  (errno:1)

It should match "string 1" and not equal to "errno:1". How can I do that using grep?

Upvotes: 2

Views: 1215

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 360605

Find any "string 1" that is not followed by "errno:1":

grep -P 'string 1(?!.*errno:1)' inputfile

Upvotes: 3

jkerian
jkerian

Reputation: 17046

I'm sure there's a way of doing it all together, but the easiest way is just to chain multiple grep commands together

cat <myfile> | grep "string 1" | grep -v "errno:1"

The -v option inverts the search, so that will display the lines that have "string 1" without "errno:1"

Upvotes: 4

Related Questions