[Resolved] How to exclude a directory in find . command?

Question:

I’m trying to run a find command for all JavaScript files, but how do I exclude a specific directory?

Here is the find code we’re using.

for file in $(find . -name '*.js')
do 
  java -jar config/yuicompressor-2.4.2.jar --type js $file -o $file
done

Answer:

Use the -prune switch. For example, if you want to exclude the misc directory just add a -path ./misc -prune -o to your find command:

find . -path ./misc -prune -false -o -name '*.txt'

Here is an example with multiple directories:

find . -type d \( -path dir1 -o -path dir2 -o -path dir3 \) -prune -false -o -name '*.txt'

Here we exclude ./dir1, ./dir2 and ./dir3 in the current directory, since in find expressions it is an action that acts on the criteria -path dir1 -o -path dir2 -o -path dir3 (if dir1 or dir2 or dir3), ANDed with type -d.

To exclude directory name at any level, use -name:

find . -type d \( -name node_modules -o -name dir2 -o -path name \) -prune -false -o -name '*.json'

If -prune doesn’t work for you, this will:

find -name "*.js" -not -path "./directory/*"

Caveat: requires traversing all of the unwanted directories.

If you like our content, please consider buying us a coffee.

Buy Me A Coffee

We are thankful for your never ending support.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.