Pete Freitag Pete Freitag

How to perform a Negative or Inverted grep search

Updated on November 07, 2024
By Pete Freitag

Grep is a great tool for search through files, or piping to a stream from another command. But what if you want to invert the match, or perform a negative grep search? Well there is a grep command line argument for that as well.

If you want to your grep command line results to only show lines of a file or stream that do not matching the pattern use the -v switch. You can also use --invert-match

Grep Example: show lines that do not contain 127.0.0.1

grep -v 127.0.0.1 file.log

The above prints lines from file.log that do not contain 127.0.0.1

We could also write this example with the --invert-match flag like this:

grep --invert-match 127.0.0.1 file.log

Negative Grep Example

Let's take a more specific example of using a negative or inverted grep search. Suppose we have a text file named grep-example.txt

This is a file named grep-example.txt
This is the second line of the grep example file,
and this is the third line.

Now suppose we want to exclude any line of the file that does not have the word example. We can perform a negative or inverted grep search for the term like this:

grep -v example grep-example.txt

The grep command would output the third line of the file:

and this is the third line.

If we do an inverted search for the term this:

grep -v this grep-example.txt

You may be thinking grep will not return anything here, since all three lines do contain the word this, however if you look closely you'll find that there is a difference in case. So in this example Grep will return the first and second line of the grep-example.txt file:

This is a file named grep-example.txt
This is the second line of the grep example file,

This is because grep is case sensitive by default. If you want to make grep case insensitive then I have another article for that which you can read.



grep linux

How to perform a Negative or Inverted grep search was first published on July 29, 2005.

If you like reading about grep, or linux then you might also like:

Discuss / Follow me on Twitter ↯