Exclude a Directory While Finding Files in Linux [Step-By-Step]

The find command in Linux is a very handy tool for finding a specific file in your machine. But sometimes, it outputs a lot of files and clutters the search result. And if you’re sure that the file you are looking for is not in a specific directory, you can actually exclude it from the search result. In this article, we will learn how can you exclude a directory from the search result of the file command.

First, let’s see what a normal output of the find command looks like. Here, I’m searching for all the files which has ‘file’ in their name, in the current directory. To do this, I’ll type :

find . -name ‘file*’
A Normal Find Command Output
A Normal Find Command Output

This lists out 3 files named file1, file2, and another file3 in the ‘new’ subdirectory, along with their full path. Here, the ‘.’ implies that the files are located in the current directory.

Exclude a Directory From the Search Result

Now, let’s say that we don’t want the ‘find’ command to find our files in the ‘new’ directory, we can simply exclude it from the search. Doing this can actually give you faster results as you won’t have to search through everything. This can be useful to you, especially if you have large folders. We can type the following command in the Terminal to achieve this:

find . -path './new' -prune -o -name 'file*'
Excluding A Directory From Search Result
Excluding A Directory From Search Result

As we can see, running this command does in fact ignore the file3 located in the test directory, but it still lists the ‘new’ folder in our result, to avoid this output we can use the following command:

find . -path './new' -prune -o -name 'file*' -print
Excluding The New Directory From Output
Excluding The New Directory From Output

As we can see, the -print the option allows us to exclude the directory name from the output.

Summary

We hope that by using this article, you were able to save your time by not searching for your files in unnecessary places. If you have any doubts or questions regarding the find command, you can always use the comment box to ask them.