Find Command Exclude Directories From Search Pattern

You can use the find command in Linux to search for files and directories, and exclude certain directories from the search pattern using the -prune option. The -prune option allows you to exclude specific directories from the search, without having to search their subdirectories.

Here is an example of how to use the find command to search for files in the current directory and exclude the node_modules directory:

$ find . -path ./node_modules -prune -o -type f -print

This command searches the current directory (.) and excludes the node_modules directory (-path ./node_modules -prune) from the search. The -o option is used to specify that the next expression (-type f) should be executed only if the previous expression (-path ./node_modules -prune) fails. The -type f option is used to search for files (f) only, and the -print option is used to print the results.

You can also exclude multiple directories by using the -prune option multiple times:

$ find . \( -path ./node_modules -o -path ./vendor \) -prune -o -type f -print

This command excludes both the node_modules and vendor directories from the search. The \( ... \) syntax is used to group the expressions together, so that the -prune option is applied to both directories.

Leave a Comment