How to exclude some directories from find command in Linux

There can be cases where you are searching for a file but you want to exclude some particular directories from the search.

-prune is used to ignore files and directories from your search

 

Lets see some examples
Exclude "work" directory in your search to find "myfile" document.

NOTE:

I have placed the same copy inside "deepak" and "work" directory

The below command will lookout for all the files with name "myfile" inside /root/

# find /root/ -name myfile -type f
/root/deepak/myfile
/root/work/myfile

To exclude "work" directory

# find /root/ -path '/root/work' -prune -o -name myfile -type f -print
/root/deepak/myfile
Also if you don't want to give complete path of the excluded directory, you can use the -name argument
# find /root/ -name 'work' -prune -o -name myfile -type f -print
/root/deepak/myfile
In the above case any directory with name "work" would be excluded from the find command

 

Excluding multiple directories from your search

Exclude any directory with name work and home

# find .  ( -name work -o -name home )  -prune -o -name myfile -type f -print

NOTE:

You can use -o argument in the shown format multiple times as many directories you want to exclude

 

To learn more about find command follow the below link
10 Practical Examples for using FIND Command in Linux

 

Related Articles
10 practical examples to use USERADD command in linux
Tutorial for Monitoring Tools SAR and KSAR with examples in Linux
Tutorial for SYSLOG with Examples in Red Hat Linux
9 examples to help you understand top command usage in Unix/Linux

 

Leave a Comment