$ 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?
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 .
xargs options : -0 : input items are terminated by null character instead of white spaces. -a file : read items from file instead of standard input.
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.
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.
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
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)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With