Linux find command exclude multiple directories
Method 1 : use option “-prune” to exclude multiple directories
find PATH \( -path "/path/todir1" -o -path "/path/todir2" \) -prune -o -name "*.txt" -print
Below is an simple test which exclude “dira” and “dirb”
j@ubuntu:~$ tree dir1 dir1 ├── dira │ └── a ├── dirb │ └── b └── dirc └── c j@ubuntu:~$ find dir1 -type d \( -path "dir1/dira" -o -path "dir1/dirb" \) -prune -o -print dir1 dir1/dirc dir1/dirc/c j@ubuntu:~$
Note: “-print” is required
-prune True; if the file is a directory, do not descend into it
Method 2 : use “!” (not) operator to not show multiple directories.
find PATH ! -path "/path/todir1/*" -! -path "/path/todir2/*" -name "*.txt" -print
Note: the “/*” is required , see below test
j@ubuntu:~$ tree dir1 dir1 ├── dira │ └── a ├── dirb │ └── b └── dirc └── c 3 directories, 3 files j@ubuntu:~$ find dir1 -type f ! -path "dir1/dira/*" ! -path "dir1/dirb/*" -print dir1/dirc/c j@ubuntu:~$
Conclusion:
Method 1 is better since it will not descend into the specified directories , for method 2 find still search those directories but just not print it out ,which means method 1 makes sense more, especially while searching huge number of files.
More find examples :Linux find command examples