Make xargs handle filenames that contain spaces

Try

find . -name \*.mp3 -print0 | xargs -0 mplayer

instead of

ls | grep mp3 

The xargs utility reads space, tab, newline and end-of-file delimited strings from the standard input and executes utility with the strings as arguments.

You want to avoid using space as a delimiter. This can be done by changing the delimiter for xargs. According to the manual:

 -0      Change xargs to expect NUL (``\0'') characters as separators,
         instead of spaces and newlines.  This is expected to be used in
         concert with the -print0 function in find(1).

Such as:

 find . -name "*.mp3" -print0 | xargs -0 mplayer

To answer the question about playing the seventh mp3; it is simpler to run

 mplayer "$(ls *.mp3 | sed -n 7p)"

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

Tags:

Shell

Find

Xargs