shellfindxargs

Make xargs handle filenames that contain spaces


$ 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?


Solution

  • 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 MacOS:

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

    The more simplistic and practically useful approach (when don't need to process the filenames further):

    mplayer *.mp3