linux - [Solved-5 Solutions] Exclude directory from find . command - ubuntu - red hat - debian - linux server - linux pc



Linux - Problem :

To run a find command for all JavaScript files, but how to exclude a specific directory ?

Here is the Code:

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

Linux - Solution 1:

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

find . -path ./misc -prune -o -name '*.txt' -print
click below button to copy the code. By - Linux tutorial - team

Here is an example with multiple directories:

find . -type d \( -path dir1 -o -path dir2 -o -path dir3 \) -prune -o -print
click below button to copy the code. By - Linux tutorial - team

Here we exclude dir1, dir2 and dir3, 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. Further action is -o print, just print.

Linux - Solution 2:

find -name "*.js" -not -path "./directory/*"
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 3:

One option would be to exclude all results that contain the directory name with grep. For example:

find . -name '*.js' | grep -v excludeddir
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 4:

$ find ./ -type f -name "pattern" ! -path "excluded path" ! -path "excluded path"
click below button to copy the code. By - Linux tutorial - team

I used this to find all files not in ".*" paths:

$ find ./ -type f -name "*" ! -path "./.*" ! -path "./*/.*"
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 5:

find ! -path "dir1" -iname "*.mp3"
click below button to copy the code. By - Linux tutorial - team

It will search for MP3 files in the current folder and subfolders except in dir1 subfolder.

Use:

find ! -path "dir1" ! -path "dir2" -iname "*.mp3"
click below button to copy the code. By - Linux tutorial - team

To exclude dir1 AND dir2


Related Searches to - linux - linux tutorial - Exclude directory from find . command