remove files when name does NOT contain some words

后端 未结 3 1171
生来不讨喜
生来不讨喜 2020-12-30 10:54

I am using Linux and intend to remove some files using shell.

I have some files in my folder, some filenames contain the word \"good\", others don\'t. For example:

相关标签:
3条回答
  • 2020-12-30 11:38

    With bash, you can get "negative" matching via the extglob shell option:

    shopt -s extglob
    rm !(*good*)
    
    0 讨论(0)
  • 2020-12-30 11:46

    This command should do what you you need:

    ls -1 | grep -v 'good' | xargs rm -f
    

    It will probably run faster than other commands, since it does not involve the use of a regex (which is slow, and unnecessary for such a simple operation).

    0 讨论(0)
  • 2020-12-30 11:54

    You can use find with the -not operator:

    find . -not -iname "*good*" -a -not -name "." -exec rm {} \;
    

    I've used -exec to call rm there, but I wonder if find has a built-in delete action it does, see below.

    But very careful with that. Note in the above I've had to put an -a -not -name "." clause in, because otherwise it matched ., the current directory. So I'd test thoroughly with -print before putting in the -exec rm {} \; bit!

    Update: Yup, I've never used it, but there is indeed a -delete action. So:

    find . -not -iname "*good*" -a -not -name "." -delete
    

    Again, be careful and double-check you're not matching more than you want to match first.

    0 讨论(0)
提交回复
热议问题