How to Use grep and Exclude Specific Files


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

You can use the following methods to do so:

Method 1: Exclude File by Name

grep -R 'Mavs' --exclude=team_info2.txt

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

Method 2: Exclude File by Extension

grep -R 'Mavs' --exclude=*.txt

This particular example will return all lines from files in the current directory that contain the pattern ‘Mavs’ while excluding any files that have a .txt extension.

The following example shows how to use each method in practice.

Example: Use grep and Exclude Specific Files

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

  • team_info1.txt
  • team_info2.txt
  • team_info3.txt

Suppose that we would like to return all lines that contain the pattern ‘Mavs’ in any of these files.

We can use the following syntax to do so:

grep -R 'Mavs'

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

This returns lines that contain the pattern ‘Mavs’ in any of the three files.

We could use the following syntax to search for lines that contain the pattern ‘Mavs’ once again but exclude the file named team_info2.txt this time:

grep -R 'Mavs' --exclude=team_info2.txt

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

grep exclude file by name

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

We could use the following syntax to search for lines that contain the pattern ‘Mavs’ once again but exclude any file that has a .txt extension this time:

grep -R 'Mavs' --exclude=*.txt

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

grep exclude file by extension

This returns no results since every file in our current directory contained .txt as the file extension.

Feel free to replace .txt with any other file extension that you would like to exclude.

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