3

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

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

and not

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

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

2

3 Answers 3

11

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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: You can use xargs -n 1 to have xargs run on one file at a time.
2

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 

1 Comment

This will fail in the (quite unlikely) case where one of the filenames contains a newline.
2

See the difference between:

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

and:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.