Post Image

Grep Exclude Pattern

When displaying a file or building a grep pipeline you will often want to exclude lines that contain a pattern versus its default behavior of including the lines that match the pattern. This is very easy to do in a simple command line switch, in this post I will demonstrate the syntax and a couple examples.

 

Syntax

$ grep -v <pattern> <filepath>

 

File

In the examples below I will be using grep against a file that contains the contents below.

This is a post about using grep
I am using this file as an example
grep can be a powerful tool
just point it at a file and watch it work

 

 

Standalone Example

In this example we will run grep against the file above and use it to exclude any line that has the word "grep" in it.

$ grep -v "grep" myfile.txt
I am using this file as an example
just point it at a file and watch it work
$

As you can see line 1 and 3 of the file contain the string "grep" so they are not displayed

 

Pipeline Example

In this example I will build a grep pipeline to exclude any line that has the word "grep" in it, but then pipe that to another grep which will display lines that include "example".

$ grep -v "grep" myfile.txt | grep "example"
I am using this file as an example
$

As you can see the only line I get from the original file this time is line 2 because we first exclude all lines with "grep" in it which leaves us with lines 2 and 4. Then we take that output and use grep to only give use lines that contain "example" which is only line 2.

 



Comments (0)
Leave a Comment