How to Exclude a Pattern with grep (With Example)


Often you may want to use the grep command in Bash to return all lines that do not contain a specific pattern.

You can use the following basic syntax to do so:

grep -v 'Mavs' points.txt

This particular example will return all lines from the file named points.txt that do not contain the pattern ‘Mavs’ anywhere in the line.

Note that we use the -v flag with grep to use an “inverted match”, i.e. select all non-matching lines.

The following example shows how to use this syntax in practice.

Example: How to Exclude a Pattern with grep

Suppose that we have a file named points.txt that contains information about points scored by various basketball players.

We can use the cat command to view the contents of this file:

Now suppose that we would like to select all lines in the file that do not contain the pattern ‘Mavs’ anywhere in the line.

We can use the following syntax to do so:

grep -v 'Mavs' points.txt

The following screenshot shows how to use this syntax in practice:

grep exclude pattern

Notice that this returns all lines from the file that do not contain ‘Mavs’ anywhere in the line.

Note that grep is case-sensitive by default.

To exclude patterns using a case-insensitive matching, you can use the -i flag as well:

grep -iv 'Mavs' points.txt

This syntax will return all lines from the file that do not contain the pattern ‘Mavs’ (in any case) anywhere in the line.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Use grep to Get Line Number of Match
How to Use grep to Extract Last Occurrence in File
How to Use grep with Case-Insensitive Matching
How to Use grep to List All Files Containing Specific String

Leave a Reply