Remove all files except some from a directory

前端 未结 19 1124
生来不讨喜
生来不讨喜 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:39

    If you're using zsh which I highly recommend.

    rm -rf ^file/folder pattern to avoid
    

    With extended_glob

    setopt extended_glob
    rm -- ^*.txt
    rm -- ^*.(sql|txt)
    
    0 讨论(0)
  • 2020-11-30 16:40

    A little late for the OP, but hopefully useful for anyone who gets here much later by google...

    I found the answer by @awi and comment on -delete by @Jamie Bullock really useful. A simple utility so you can do this in different directories ignoring different file names/types each time with minimal typing:

    rm_except (or whatever you want to name it)

    #!/bin/bash
    
    ignore=""
    
    for fignore in "$@"; do
      ignore=${ignore}"-not -name ${fignore} "
    done
    
    find . -type f $ignore -delete
    

    e.g. to delete everything except for text files and foo.bar:

    rm_except *.txt foo.bar 
    

    Similar to @mishunika, but without the if clause.

    0 讨论(0)
  • 2020-11-30 16:41
    find [path] -type f -not -name 'textfile.txt' -not -name 'backup.tar.gz' -delete
    

    If you don't specify -type f find will also list directories, which you may not want.


    Or a more general solution using the very useful combination find | xargs:

    find [path] -type f -not -name 'EXPR' -print0 | xargs -0 rm --
    

    for example, delete all non txt-files in the current directory:

    find . -type f -not -name '*txt' -print0 | xargs -0 rm --
    

    The print0 and -0 combination is needed if there are spaces in any of the filenames that should be deleted.

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

    This is similar to the comment from @siwei-shen but you need the -o flag to do multiple patterns. The -o flag stands for 'or'

    find . -type f -not -name '*ignore1' -o -not -name '*ignore2' | xargs rm

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

    Remove everything exclude file.name:

    ls -d /path/to/your/files/* |grep -v file.name|xargs rm -rf
    
    0 讨论(0)
  • 2020-11-30 16:44

    Make the files immutable. Not even root will be allowed to delete them.

    chattr +i textfile.txt backup.tar.gz script.php database.sql info.txt
    rm *
    

    All other files have been deleted.
    Eventually you can reset them mutable.

    chattr -i *
    
    0 讨论(0)
提交回复
热议问题