Delete a list of files with find and grep

后端 未结 9 1671
一个人的身影
一个人的身影 2021-01-30 08:44

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

9条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 09:10

    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.

提交回复
热议问题