Remove all files except some from a directory

前端 未结 19 1185
生来不讨喜
生来不讨喜 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 17:00

    You can do this with two command sequences. First define an array with the name of the files you do not want to exclude:

    files=( backup.tar.gz script.php database.sql info.txt )
    

    After that, loop through all files in the directory you want to exclude, checking if the filename is in the array you don't want to exclude; if its not then delete the file.

    for file in *; do
      if [[ ! " ${files[@]} " ~= "$file"  ]];then
        rm "$file"
      fi
    done
    

提交回复
热议问题