looping through files with spaces in the filenames in bash

By thomas, 16 May, 2006

I sometimes have to transfer files with spaces in the names, I like using a for loop, but the usual way doesn't work.

Usual way:

for file in `find . -type f|grep .ext$` do /do/something/to $file done

To get around this I use a while loop with a read instead. Using the read will read to the end of the line, enclosing within quotes escapes the spaces.

Unusual way:

find . -type f|grep .ext$ |while read file do /do/something/to "$file" done 

Or if you don't like using more than one line...and enjoy the unreadable (I'm transferring all my avi files to another computer in this example)

find . -name \*.avi |while read file; do scp "$file" 172.16.1.1:; done

The above could be done using find -exec as well:

find . -name \*.avi -exec scp "{}" 172.16.1.1: \;