使用sudo rm -r时,如何删除除以下文件外的所有文件?

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

当前回答

只是:

rm $(ls -I "*.txt" ) #Deletes file type except *.txt

Or:

rm $(ls -I "*.txt" -I "*.pdf" ) #Deletes file types except *.txt & *.pdf

其他回答

因为没人提过

把不想删除的文件复制到安全的地方 删除所有文件 将复制的文件移回原位

在Bash中可以使用GLOBIGNORE环境变量。

假设您想删除除php和sql之外的所有文件,那么您可以执行以下操作-

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

像这样设置GLOBIGNORE会忽略php和sql中的通配符,比如“ls *”或“rm *”。因此,在设置变量后使用“rm *”将只删除txt和tar.gz文件。

假设具有这些名称的文件存在于目录树中的多个位置,并且您希望保存所有这些文件:

find . -type f ! -regex ".*/\(textfile.txt\|backup.tar.gz\|script.php\|database.sql\|info.txt\)" -delete

试着这样做:

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

但是带空格的名字(一如既往)很难取。也尝试用Virtualbox\ VMs代替引号。它总是删除该目录(Virtualbox vm)。

你可以为它写一个for循环…%)

for x in *
do
        if [ "$x" != "exclude_criteria" ]
        then
                rm -f $x;
        fi
done;