Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make xargs handle filenames that contain spaces

Tags:

find

shell

xargs

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

like image 355
showkey Avatar asked May 26 '13 10:05

showkey


People also ask

How do I CP with xargs?

We can use xargs to allow us to copy files to multiple locations with a single command. We are going to pipe the names of two directories into xargs as the input parameters. We'll tell xargs to only pass one of these parameters at a time to the command it is working with. In this case, the command is cp .

What xargs 0?

xargs options : -0 : input items are terminated by null character instead of white spaces. -a file : read items from file instead of standard input.

What does the xargs command do?

The xargs command builds and executes commands provided through the standard input. It takes the input and converts it into a command argument for another command. This feature is particularly useful in file management, where xargs is used in combination with rm , cp , mkdir , and other similar commands.

What is xargs WC?

wc combines the total lines of all files that were passed to is as arguments. xargs collects lines from input and puts them all at once as one set of multiple arguments to wc so you get the total of all those files.


2 Answers

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 
like image 197
Ray Avatar answered Oct 20 '22 04:10

Ray


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)" 
like image 25
Jens Avatar answered Oct 20 '22 06:10

Jens