Is it possible to exclude a directory with find command? Exclude directories while doing running find command?
Yep, the command FIND has wide range of options to search what you actually looking for. I have already listed different switches and its usages with examples. Here we go for excluding some directories from our find job.
In some cases, we have to exclude some directories from our search pattern to improve the search speed or efficiency. If the server has a lot of directories and we are sure about that the file / directory that we are searching is not in some directories, we can directly exclude those to improve the performance. The result will be faster as compared to the full search.
Quick view on “Find command and switches“
There are different ways to exclude a directory or multiple directories in FIND command. Here I’m listing some methods!
To explain this, I created the following directories and files:
- “cry“, “bit” and “com” directories.
- ” findme “: The test file in all directories.
Lets see the output:
# find -iname findme ./bit/findme ./com/findme ./cry/findme
Method 1 : Using the option “-prune -o”
We can exclude directories by using the help of “path“, “prune“, “o” and “print” switches with find command.
See the example:
# find ./ -path ./bit/* -prune -o -iname findme -print ./com/findme ./cry/findme
The directory “bit” will be excluded from the find search!
Method 2 : Using “! -path”
This is not much complicated compared to first method. See the example pasted below:
# find -iname findme ! -path ./bit/* ./com/findme ./cry/findme
Method 3 : Simple 🙂
Yes, it’s very simple. We can ignore the location by using inverse grep “grep -v” option.
See the example:
# find -iname findme|grep -v bit ./com/findme ./cry/findme
Excluding multiples directories
Similar way we can exclude multiple directories also. See the sample outputs:
# find -iname findme ! -path ./bit/* ! -path ./cry?* ./com/findme
# find -iname findme | egrep -v "bit|cry" ./com/findme
That’s it. Compose it your own ways!!
1, 10+ commonly using find command switches with example Unix/Linux
2, How to find the total number of connections for a cPanel account from the log files
3, How to check all opened files in a directory – lsof command