How to Exclude Multiple Patterns with grep


Often you may want to use the grep command in Bash to return all lines that do not contain one of several specific patterns.

You can use the following basic syntax to do so:

grep -Ev 'Mavs|Celtics' points.txt

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

Note that we use the -E flag with grep to specify that we are using an extended regular expression.

Also note that we use the -v flag 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 Multiple Patterns 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’ or the pattern ‘Celtics’ anywhere in the line.

We can use the following syntax to do so:

grep -Ev 'Mavs|Celtics' points.txt

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

grep exclude multiple patterns

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

Note that we use the | symbol as an “OR” operator and we can string together as many of these operators as we’d like to exclude even more patterns.

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