You are here

Handling file names with spaces when using xargs

Submitted by Druss on Sat, 2011-07-30 13:11

I've previously written a short tip on how to perform batch rename operations using ls, sed, and xargs. One of the issues with xargs is that it breaks down when dealing with filenames which include spaces as it assumes that each word in the filename is a separate argument. Looking around on the Internet threw up a number of solutions mostly utilising find and xargs with the -print0 and -0 switches respectively. However, when it comes to ls, there's a far simpler solution: quoting. The -Q provided by ls quotes the filenames in the output. In other words, the example from the other article:
ls | sed -e 'p;s/^/0/' | xargs -n2 mv
would become:
ls -Q | sed -e 'p;s/^/0/' | xargs -n2 mv

Once quoted, xargs and Linux treat the filename within as a single entity, thereby solving our little problem.

Hope this helps somebody out there :)