‘xargs’ – Handling Filenames With Spaces or Other Special Characters

xargs is a great little utility to perform batch operations on a large set of files. Typically, the results of a find operation are piped to the xargs command:
   find . -iname "*.pdf" | xargs -I{} mv {} ~/collections/pdf/
The -I{} tells xargs to substitute '{}' in the statement to be executed with the entries being piped through. If these entries have spaces or other special characters, though, things will go awry. For example, filenames with spaces in them passed to xargs will result in xargs barfing with a "xargs: unterminated quote" error on OS X. The solution is use null-terminated strings in both the find and xargs invocation:
   find . -iname "*.pdf" -print0 | xargs -0 -I{} mv {} ~/collections/pdf/
Note the -print0 argument to find, and the corresponding -0 argument to xargs: the former tells find to produce null-terminated entries while the latter tells xargs to expect and consume null-terminated entries.

Leave a Reply

Your email address will not be published. Required fields are marked *