This config shows some examples of find command allowing you to exclude directories explicitly from its search. Below you can find our sandbox directory containing multiple directories and files:
. ├── dir1 │ ├── dir2 │ │ └── dir3 │ │ └── file2 │ └── file1 ├── dir4 │ └── file3 └── dir5 └── dir6 ├── dir4 │ └── file4 └── file4 7 directories, 5 files
In the first example below we use find’s -prune
option to exclude dir4
directory located in a current working directory
$ find . -path ./dir4 -prune -o -print . ./dir1 ./dir1/dir2 ./dir1/dir2/dir3 ./dir1/dir2/dir3/file2 ./dir1/file1 ./dir5 ./dir5/dir6 ./dir5/dir6/file4 ./dir5/dir6/dir4 ./dir5/dir6/dir4/file4
Our sandbox directory tree contains two directories named dir4
. However, the above command only excluded a single directory located in our current working directory. The following linux command will list only directory types and can be used to exclude both dir4
directories:
$ find . -type d \( ! -name dir4 \) -print . ./dir1 ./dir1/dir2 ./dir1/dir2/dir3 ./dir5 ./dir5/dir6
The last example will show how to use find command to copy all files but excluding a directories from its search.
$ find . -type f -not -path "./dir1/*" -not -path "./dir4/*" -exec cp '{}' /tmp \;
The above command will find recursively and copy all files into /tmp
directory from a current working directory and at the same time it will exclude dir1
and dir2
directories from its search.