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
I found the functions name in C sources files exclude *.o and exclude *.swp and exclude (not regular file) and exclude dir output with this command:
There are plenty of good answers, it just took me some time to understand what each element of the command was for and the logic behind it.
find will start finding files and directories in the current directory, hence the
find .
.The
-o
option stands for a logical OR and separates the two parts of the command :Any directory or file that is not the ./misc directory will not pass the first test
-path ./misc
. But they will be tested against the second expression. If their name corresponds to the pattern*.txt
they get printed, because of the-print
option.When find reaches the ./misc directory, this directory only satisfies the first expression. So the
-prune
option will be applied to it. It tells the find command to not explore that directory. So any file or directory in ./misc will not even be explored by find, will not be tested against the second part of the expression and will not be printed.Better use the
exec
action than thefor
loop:The
exec ... '{}' ... '{}' \;
will be executed once for every matching file, replacing the braces'{}'
with the current file name.Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation*.
Notes
* From the EXAMPLES section of the
find (GNU findutils) 4.4.2
man pageOne option would be to exclude all results that contain the directory name with grep. For example:
To exclude multiple directories:
To add directories, add
-o -path "./dirname/*"
:But maybe you should use a regular expression, if there are many directories to exclude.
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:Here is an example with multiple directories:
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 withtype -d
. Further action is-o print
, just print.