Remove all files except some from a directory

前端 未结 19 1126
生来不讨喜
生来不讨喜 2020-11-30 16:36

When using sudo rm -r, how can I delete all files, with the exception of the following:

textfile.txt
backup.tar.gz
script.php
database.sql
info.         


        
相关标签:
19条回答
  • 2020-11-30 16:46

    Rather than going for a direct command, please move required files to temp dir outside current dir. Then delete all files using rm * or rm -r *.

    Then move required files to current dir.

    0 讨论(0)
  • 2020-11-30 16:47
    rm !(textfile.txt|backup.tar.gz|script.php|database.sql|info.txt)
    

    The extglob (Extended Pattern Matching) needs to be enabled in BASH (if it's not enabled):

    shopt -s extglob
    
    0 讨论(0)
  • 2020-11-30 16:52

    You can use GLOBIGNORE environment variable in Bash.

    Suppose you want to delete all files except php and sql, then you can do the following -

    export GLOBIGNORE=*.php:*.sql
    rm *
    export GLOBIGNORE=
    

    Setting GLOBIGNORE like this ignores php and sql from wildcards used like "ls *" or "rm *". So, using "rm *" after setting the variable will delete only txt and tar.gz file.

    0 讨论(0)
  • 2020-11-30 16:53

    I belive you can use

    rm -v !(filename)
    

    Except for the filename all the other files will e deleted in the directory and make sure you are using it in

    0 讨论(0)
  • 2020-11-30 16:57

    Since nobody mentioned it:

    • copy the files you don't want to delete in a safe place
    • delete all the files
    • move the copied files back in place
    0 讨论(0)
  • 2020-11-30 16:57

    Trying it worked with:

    rm -r !(Applications|"Virtualbox VMs"|Downloads|Documents|Desktop|Public)
    

    but names with spaces are (as always) tough. Tried also with Virtualbox\ VMs instead the quotes. It deletes always that directory (Virtualbox VMs).

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