Take the 2-minute tour ×

Here is something strange.

mkdir -p "1/2 3/4"
touch 1/2\ 3/4/file.jpg
for f in $(find . -type f -name \*jpg); do echo "${f}"; done

This returns


and not

./1/2 3/4/file.jpg

How do I get find for preserve white spaces so the file path is correct?

share|improve this question

3 Answers 3

up vote 3 down vote accepted

It can be done in several ways, but I find it much better to do it this way:

find . -type f -name \*.jpg | while read i ; do echo "Procesing $i..." ; done
share|improve this answer
This will fail in the (quite unlikely) case where one of the filenames contains a newline. –  a3nm May 19 '11 at 1:00

You can use the -print0 option along with xargs -0. For instance:

find . -type f -name \*.jpg -print0 | xargs -0 echo

This would work no matter the content of the file names (even newlines would be handled correctly).

share|improve this answer
I was going to suggest this too, however this groups as many filenames together as it can (as will fit on a command line) and executes the command for each batch, not for each file. That's probably a better thing to do instead of a for loop anyway, or find . -type f -name \*.jpg -exec something {} \+ (note the \+ instead of \;) –  Stephen P May 19 '11 at 1:00
@Stephen: You can use xargs -n 1 to have xargs run on one file at a time. –  camh May 19 '11 at 9:06
@camh: thanks, I always forget about that. –  Stephen P May 19 '11 at 22:00

See the difference between:

find . -type f -name \*.jpg -exec echo {} \;


find . -type f -name \*.jpg -exec echo \"{}\" \;
share|improve this answer

Your Answer


