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
For what I needed it worked like this, finding
landscape.jpg
in all server starting from root and excluding the search in/var
directory:find / -maxdepth 1 -type d | grep -v /var | xargs -I '{}' find '{}' -name landscape.jpg
find / -maxdepth 1 -type d
lists all directories in/
grep -v /var
excludes `/var' from the listxargs -I '{}' find '{}' -name landscape.jpg
execute any command, likefind
with each directory/result from listI find the following easier to reason about than other proposed solutions:
This comes from an actual use case, where I needed to call yui-compressor on some files generated by wintersmith, but leave out other files that need to be sent as-is.
Inside
\(
and\)
is an expression that will match exactlybuild/external
(it will not match if you didfind ./build
, for example -- you need to change it to./build/external
in that case), and will, on success, avoid traversing anything below. This is then grouped as a single expression with the escaped parenthesis, and prefixed with-not
which will makefind
skip anything that was matched by that expression.One might ask if adding
-not
will not make all other files hidden by-prune
reappear, and the answer is no. The way-prune
works is that anything that, once it is reached, the files below that directory are permanently ignored.That is also easy to expand to add additional exclusions. For example:
I was using
find
to provide a list of files forxgettext
, and wanted to omit a specific directory and its contents. I tried many permutations of-path
combined with-prune
but was unable to fully exclude the directory which I wanted gone.Although I was able to ignore the contents of the directory which I wanted ignored,
find
then returned the directory itself as one of the results, which causedxgettext
to crash as a result (doesn't accept directories; only files).My solution was to simply use
grep -v
to skip the directory that I didn't want in the results:Whether or not there is an argument for
find
that will work 100%, I cannot say for certain. Usinggrep
was a quick and easy solution after some headache.I tried command above, but none of those using "-prune" works for me. Eventually I tried this out with command below:
Use the -prune option. So, something like:
The '-type d -name proc -prune' only look for directories named proc to exclude.
The '-o' is an 'OR' operator.
how-to-use-prune-option-of-find-in-sh is an excellent answer by Laurence Gonsalves on how
-prune
works.And here is the generic solution:
To avoid typing
/path/to/seach/
multiple times, wrap thefind
in apushd .. popd
pair.