I want to delete all files which have names containing a specific word, e.g. \"car\". So far, I came up with this:
find|grep car
How do I pass
You really want to use find
with -print0
and rm
with --
:
find [dir] [options] -print0 | grep --null-data [pattern] | xargs -0 rm --
A concrete example (removing all files below the current directory containing car in their filename):
find . -print0 | grep --null-data car | xargs -0 rm --
Why is this necessary:
-print0
, --null-data
and -0
change the handling of the input/output from parsed as tokens separated by whitespace to parsed as tokens separated by the \0
-character. This allows the handling of unusual filenames (see man find
for details)rm --
makes sure to actually remove files starting with a -
instead of treating them as parameters to rm
. In case there is a file called -rf
and do find . -print0 | grep --null-data r | xargs -0 rm
, the file -rf
will possibly not be removed, but alter the behaviour of rm on the other files.