[svlug] Working with spaces in shell scripts

William R Ward bill at wards.net
Tue Dec 14 16:09:24 PST 2004

Fabrizio Bertocci writes:
>Never give up ...
>Usually if you enclose in double quotes (") the variable that contains
>the directory name, it works...
>   foo="Monkey Joe"
>   rm "$foo/abc.txt"
>Unfortunately the following command won't work:
>   for i in `find /my_root -type f`; do ...
>because there's no way to distinguish between a space in the directory
>name and the separator between two files.
>In this case you can use the 'find' command with the -exec option: the
>following command removes all the files ending with '.txt' from
>/my_root directory and all the sub-dirs, including directories that
>contains spaces:
>   find /my_root -type f -name "*.txt" -exec rm -f {} \;

Another option is
    find /my_root -type f -name "*.txt" -print0 | xargs -0 rm -f

Using the xargs command is generally faster since it doesn't have to
invoke "rm" for each and every file.  But because paths may contain
spaces you would need to use the -0 option along with find's -print0
option to use null-terminated rather than whitespace-terminated
filenames in the output of find.

Note that these options (find -print0 and xargs -0) may not be present
on all Unix systems.  They are features of newer GNU utilities only.


PS: Fabrizio, it is customary on this list to post your reply *after*
the quoted text, and to trim the parts you aren't replying to.

William R Ward               bill at wards.net             http://bill.wards.net
   Help save the San Jose Earthquakes - http://www.soccersiliconvalley.com/

More information about the svlug mailing list