Make xargs handle filenames that contain spaces

showkey picture showkey · May 26, 2013 · Viewed 104.9k times · Source
$ ls *mp3 | xargs mplayer  

Playing Lemon.  
File not found: 'Lemon'  
Playing Tree.mp3.  
File not found: 'Tree.mp3'  

Exiting... (End of file)  

My command fails because the file "Lemon Tree.mp3" contains spaces and so xargs thinks it's two files. Can I make find + xargs work with filenames like this?

Answer

Ray picture Ray · Sep 15, 2015

The xargs command takes white space characters (tabs, spaces, new lines) as delimiters.

You can narrow it down only for the new line characters ('\n') with -d option like this:

ls *.mp3 | xargs -d '\n' mplayer

It works only with GNU xargs.

For BSD systems, use the -0 option like this:

ls *.mp3 | xargs -0 mplayer

This method is simpler and works with the GNU xargs as well.

For MacOS:

ls *.mp3 | tr \\n \\0 | xargs -0 mplayer