How to Exclude a Directory While Finding Files in Linux

In Linux, the find command is used to search for files or folders from the command line. It is a complex command and has a large number of options, arguments, and modes.

The most common use of the find command is to search for files using either a regular expression or the complete filename(s) to be searched.

[ You might also like: How to Find Files Containing Specific Text String in Linux ]

For example, to search for files with names starting with ‘file_’, we can run:

$ find . -name 'file_*'
Search Files with Filenames
Search Files with Filenames

As you can see above, it outputs the full paths of the files which are returned by the search. Here, the '.' implies the current directory. Find will search for the filename pattern in the current directory, all subdirectories, and so on till the deepest level of the file structure. Similarly, you can have any other directory in place of '.'.

Exclude a Directory While Searching Files

Now, there can be scenarios when a user is sure that a certain folder or folders do not contain the file to be searched for. Hence, it is a good idea to exclude such folders from the search, so that the command returns the results faster.

To exclude a directory from search, use the '-prune' argument:

$ find . -name './test' -prune -o -name 'file_*'

Let’s first analyze what’s going on here.

The part "-name './test' -prune" implies: exclude the folder ‘test’ from searching. After that, '-o' tells the command: what else should be done once the command excludes ‘test’. We simply pass the pattern described in the earlier example here.

This pattern will now run on all folders, except ‘test’.

Exclude Directory in Find Command
Exclude Directory in Find Command

You can now see that the search is indeed excluding the folder ‘test’. However, the folder name itself is getting printed.

Exclude a Directory Name from Find Output

To avoid this, simply append '-print' at the end. This option will exclude the directory name from the output.

$ find . -name './test' -prune -o -name 'file_*' -print
Exclude Directory Name in Find Command
Exclude Directory Name in Find Command

The pattern has now looked for files in the current directory and excluded the ‘test’ directory.

Conclusion

In this article, we have seen how to exclude a directory when searching for files using the find command. Note that the examples given in this article are searching files based on filenames ('-name'). There are many other ways to search for files as well within the find command. Make sure you refer to the man page of the find command to explore them in-depth.

Thanks for reading and feel free to leave feedback or questions in the comments below.

Got something to say? Join the discussion.