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

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

当前回答

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

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

其他回答

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

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

我正在寻找的答案是运行脚本,但我希望避免删除脚本本身。因此,如果有人正在寻找类似的答案,请执行以下步骤。

创建一个.sh文件并编写以下代码:

    cp my_run_build.sh ../../ 
    rm -rf * cp  
    ../../my_run_build.sh . 
    /*amend rest of the script*/

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

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

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

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

使文件不可变。即使root用户也不允许删除它们。

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

所有其他文件都已删除。 最终你可以将它们重置为可变的。

chattr -i *

试着这样做:

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

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