Bash: Use find Command and Exclude Specific Directory


Often you may want to use the find command in Bash to find files that match a specific pattern while excluding a specific directory when searching.

You can use the following syntax to do so:

find -name "*.txt" -not -path "./central_data/*"

This particular example will find all files that end in .txt in the current directory while excluding the directory named central_data when searching.

Note that you can also use the -not operator multiple times to exclude multiple directories at once:

find -name "*.txt" -not -path "./central_data/*" -not -path "./east_data/*"

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

Example: How to Use find Command and Exclude Specific Directory in Bash

Suppose that we would like to find all files in our current directory that contain .txt as the file extension.

We can use the following syntax to do so:

find -name "*.txt"

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

This returns the names of all files in all subfolders that contain .txt as the file extension.

Suppose instead that we would like to find all files with .txt as the file extension but exclude the directory named central_data when searching.

We can use the following syntax to do so:

find -name "*.txt" -not -path "./central_data/*"

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

Bash find exclude directory

Notice that this returns all files that have a .txt extension, excluding any files located in the central_data subfolder.

Note that we could also use the following syntax to exclude both the central_data and east_data subfolders when searching for .txt files:

find -name "*.txt" -not -path "./central_data/*" -not -path "./east_data/*"

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

Bash find exclude multiple directories

This returns all files that have a .txt extension, excluding any files located in the central_data and east_data subfolders.

Feel free to use the -not operator as many times as you would like to exclude as many folders as you’d like when searching for files.

Related Tutorials

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

Bash: How to Use find -exec with grep
Bash: How to Filter for Lines in File that Start with Specific String
Bash: How to Filter CSV File Based on Column Value

Leave a Reply