Shell Scripting – How to Delete Files with Spaces in Their Names

quotingrmshellxargs

I am trying to delete all the files with a space in their names. I am using following command. But it is giving me an error

Command : ls | egrep '. ' | xargs rm

Here if I am using only ls | egrep '. ' command it is giving me all the file name with spaces in the filenames. But when I am trying to pass the output to rm, all the spaces (leading or trailing) gets deleted. So my command is not getting properly executed.

Any pointers on how to delete the file having atleast one space in their name?

Best Answer

You can use standard globbing on the rm command:

rm -- *\ *

This will delete any file whose name contains a space; the space is escaped so the shell doesn't interpret it as a separator. Adding -- will avoid problems with filenames starting with dashes (they won’t be interpreted as arguments by rm).

If you want to confirm each file before it’s deleted, add the -i option:

rm -i -- *\ *
Related Question