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

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

当前回答

您可以使用两个命令序列来完成此操作。 首先定义一个数组,其中包含你不想排除的文件的名称:

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

在此之后,循环遍历你想要排除的目录中的所有文件,检查文件名是否在你不想排除的数组中;如果不是,然后删除文件。

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

其他回答

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

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

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

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

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

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

这类似于@siwei-shen的评论,但是您需要-o标志来处理多个模式。-o标志代表'or'

找到。-o -not -name '*ignore2' | xargs rm . type f -not -name '*ignore1' -o -not -name '*ignore2

不要直接执行命令,请将所需文件移动到当前目录之外的临时目录。然后使用rm *或rm -r *删除所有文件。

然后移动所需的文件到当前目录。

试着这样做:

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

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