The technique I use most often is find | xargs
. For example, if you want to make every file in this directory and all of its subdirectories world-readable, you can do:
find . -type f -print0 | xargs -0 chmod go+r
find . -type d -print0 | xargs -0 chmod go+rx
The -print0
option terminates with a NULL character instead of a space. The -0
option splits its input the same way. So this is the combination to use on files with spaces.
You can picture this chain of commands as taking every line output by find
and sticking it on the end of a chmod
command.
If the command you want to run as its argument in the middle instead of on the end, you have to be a bit creative. For instance, I needed to change into every subdirectory and run the command latemk -c
. So I used (from Wikipedia):
find . -type d -depth 1 -print0 | \
xargs -0 sh -c 'for dir; do pushd "$dir" && latexmk -c && popd; done' fnord
This has the effect of for dir $(subdirs); do stuff; done
, but is safe for directories with spaces in their names. Also, the separate calls to stuff
are made in the same shell, which is why in my command we have to return back to the current directory with popd
.