Pipe the output of a command to rm command

To answer your more general question, that's the job of xargs to take a list of words on standard input and convert it to a list of arguments to a command.

However, xargs expects the list as a space, tab and newline (and possibly more blank characters depending on the locale and xargs implementation) separated list of words where single quotes, double quotes and backslash are used to escape those separators (with varying behaviors with regards to nesting of those by different implementations of xargs).

If the input is a newline-terminated list, the canonical way to convert it to the format expected by xargs is to escape every character (though only, backslash, single quote, double quote, underscore (potentially), space and tab (and possibly other blanks if not in the C locale) are necessary) but newline with a backslash character, which we can do with sed.

mpc | head -n 1 | sed 's/./\\&/g' | xargs rm --

Note that some xargs implementations have a rather low limit on the maximum line length they expect on stdin, so you may want to only escape the necessary characters with those.

With GNU xargs at least, you don't need to do that, you can do:

mpc | head -n 1 | xargs -rd '\n' rm --

(also using the GNU specific -r option to avoid running any command if the input is empty).


You can do this with rm -i "/path/to/music/library/$(mpc -f %file% | head -n 1)". However, be warned that this will break if the filename contains a newline. As the output of mpc -f %file% is relative to your music library path, you need to prepend it to the output.

Tags:

Command Line