Open In App

How to Exclude Certain Paths With the find Command in Linux

Improve
Improve
Like Article
Like
Save
Share
Report

The find command in Linux is a very useful command line utility that helps us in finding files and directories. In our daily life, there are many tasks in which we require files that may be located deep inside the system, finding them manually would be a tedious task. Thus, the find command comes in handy.

We can improve the performance of this command by excluding certain files and directories so that it doesn’t look into them.

Ways to exclude paths with the find command:

Method 1: The -prune flag

Syntax:

find <path_of_the_file> -prune

For the sake of this article, we will be creating sample files and directories which will be used for demonstration purposes.

mkdir dir1 dir2 dir3
touch dir1/cat dir1/dog dir1/ant
touch dir2/apple dir2/cherry dir2/grape
touch dir3/car dir3/bus dir3/bike
How to Exclude Certain Paths With the find Command in Linux

 

Let us look at the tree of this directory system: (install the tree command by sudo apt install tree)

 

Now we will use the -prune option to exclude a certain path while searching:

find . -path ./dir3 -prune -o -print

This will enable the system to look for all the directories except the dir3 directory.

How to Exclude Certain Paths With the find Command in Linux

 

For simplicity we have put all three directories within a sample directory so that all the files in the system are not searched, otherwise, the list would be too long. The result from the output is clear that dir3 was excluded and all the remaining directories were printed.

Excluding multiple directories:

We can also exclude multiple paths if we want to :

find . \( -path ./dir1 -prune -o -path ./dir3 -prune \) -o -print

 

Both directories have been excluded from the search.

Method 2: The -not flag

The -not flag can also be used to exclude directories from the scope of search:

Syntax:

find . -type f -not -path '*/directory_name/*'

Let us exclude dir1 from the search scope:

find . -type f -not -path '*/dir1/*'

 

The not flag also excluded the dir1 directory, although its syntax is a bit complex it performs the same action.

Method 3: The “!” operator

The ! flag like the prune and not flags can be used to exclude the path:

Syntax:

find . -type f  !  -path '*/directory_name/*'

Let us exclude the dir2 directory now:

find . -type f  !  -path '*/dir2/*'

 

With the help of ! operator the second directory(dir2) was not searched.

So these were the three ways in which you can exclude certain paths from the scope of the find command.


Last Updated : 01 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads