From man xargs
xargs reads items from the standard input, delimited by blanks (which
can be protected with double or single quotes or a backslash) or
newlines, and executes the command (default is /bin/echo) one or more
times with any initial-arguments followed by items read from standard
input. Blank lines on the standard input are ignored.
We can (mostly) fix your initial command by changing the xargs delimiter to a newline:
ls | egrep '. ' | xargs -d '\n' rm
(don't do this... read on)
But what if the filename contains a newline?
touch "filename with blanks
and newline"
Because Unix filenames can contain blanks and newlines, this default
behaviour is often problematic; filenames containing blanks and/or
newlines are incorrectly processed by xargs. In these situations it is
better to use the -0 option, which prevents such problems.
ls
is really a tool for direct consumption by a human, instead we need to use the find
command which can separate the filenames with a null character (-print0
). We also need to tell grep to use null characters to separate the input (-z
) and output (-Z
). Finally, we tell xargs to also use null characters (-0
)
find . -type f -print0 | egrep '. ' -z -Z | xargs -0 rm
echo
first, to guard from typos. Addecho
at the front and it will print out all the files it's going to remove. – Riking Jun 08 '15 at 03:00find
is powerful, sometimes you don't need to kill the chicken with a machine gun. UNIX administrators would generally not resort tofind
to (for example) "remove all files beginning with the letter A"... one would simplyrm A*
. Likewise to remove files containing spaces, rm can do the job. In other words, don't be fooled because space is invisible and is treated specially by the shell. Simply escape it, as Stephen Kitt has done, and you can think of it like any other character. – Mike S Jun 08 '15 at 19:17