Delete a list of files with find and grep

后端 未结 9 1665
一个人的身影
一个人的身影 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 08:54

    I like to use

    rm -rf $(find . | grep car)

    It does exactly what you ask, logically running rm -rf on the what grep car returns from the output of find . which is a list of every file and folder recursively.

    0 讨论(0)
  • 2021-01-30 08:59

    A bit of necromancy, but you can also use find, grep, and xargs

    find . -type f | grep -e "pattern1" -e "pattern2" | xargs rm -rf
    

    ^ Find will need some attention to make it work for your needs potentially, such as is a file, mindepth, maxdepth and any globbing.

    0 讨论(0)
  • 2021-01-30 09:03

    You can use ls and grep to find your files and rm -rf to delete the files.

    rm -rf $(ls | grep car)
    

    But this is not a good idea to use this command if there is a chance of directories or files, you don't want to delete, having names with the character pattern you are specifying with grep.

    0 讨论(0)
  • 2021-01-30 09:03
    find start_dir -iname \*car\* -exec rm -v {} \;
    
    0 讨论(0)
  • 2021-01-30 09:07

    To view what you are going to delete first, since rm -fr is such a dangerous command:

    find /path/to/file/ | grep car | xargs ls -lh
    

    Then if the results are what you want, run the real command by removing the ls -lh, replacing it with rm -fr

    find /path/to/file/ | grep car | xargs rm -fr
    
    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题