How to Use grep and Exclude Specific Directories


Often you may want to use the grep command in Bash to search for lines in files that match patterns, while excluding specific directories.

You can use the following methods to do so:

Method 1: Use grep and Exclude One Directory

grep -R 'Mavs' --exclude-dir=coaches

This particular example will return all lines from files in the current directory that contain the pattern ‘Mavs’ while excluding files from the directory named coaches.

Method 2: Use grep and Exclude Multiple Directories

grep -R 'Mavs' --exclude-dir={coaches,teams}

This particular example will return all lines from files in the current directory that contain the pattern ‘Mavs’ while excluding files from the directories named coaches or teams.

The following examples show how to use each method in practice.

Example: Use grep and Exclude Specific Directories

Suppose that our current directory has the the following three subdirectories:

  • coaches
  • managers
  • teams

Suppose that we would like to return all lines that contain the pattern ‘Mavs’ in any file in this directory.

We can use the following syntax to do so:

grep -R 'Mavs'

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

Notice that this returns some lines from files in each of the three directories.

We could use the following syntax to search for lines that contain the pattern ‘Mavs’ once again but exclude the directory named coaches and teams this time:

grep -R 'Mavs' --exclude-dir=coaches

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

grep exclude directory

This returns the lines that contain ‘Mavs’ in any file in each directory, excluding the coaches directory.

We could use the following syntax to search for lines that contain the pattern ‘Mavs’ once again but exclude the directories named coaches and teams this time:

grep -R 'Mavs' --exclude-dir={coaches,teams}

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

grep exclude multiple directories

This returns the lines that contain ‘Mavs’ in any file in each directory, excluding the coaches and teams directories.

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