Remove all files except some from a directory

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

提交回复
热议问题