Mika H.
Mika H.

Reputation: 4339

grep without string

I want to find all the lines in my text file containing the string "abc", but not containing the string "def". Can I use the grep command to accomplish this task?

Upvotes: 33

Views: 55934

Answers (2)

alex
alex

Reputation: 490461

This might do it.

fgrep "abc" file | grep -v "def"

Upvotes: 4

sampson-chen
sampson-chen

Reputation: 47327

Either of the these will do:

grep -v "def" input_file | grep "abc"

or

grep "abc" input_file | grep -v "def"

The following will also preserve coloring if you only want to see the output on stdout:

grep --color=always "abc" input_file | grep -v "def"

The -v option (stands for "invert match") tells grep to ignore the lines with the specified pattern - in this case def.

Upvotes: 57

Related Questions