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

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

当前回答

find [path] -type f -not -name 'textfile.txt' -not -name 'backup.tar.gz' -delete

如果不指定-type f find也会列出目录,这可能不是您想要的。


或者一个更通用的解决方案,使用非常有用的组合find | xargs:

find [path] -type f -not -name 'EXPR' -print0 | xargs -0 rm --

例如,删除当前目录下的所有非txt文件:

find . -type f -not -name '*txt' -print0 | xargs -0 rm --

如果需要删除的文件名中有空格,则需要print0和-0组合。

其他回答

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

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

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

chattr -i *

因为没人提过

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

find [path] -type f -not -name 'textfile.txt' -not -name 'backup.tar.gz' -delete

如果不指定-type f find也会列出目录,这可能不是您想要的。


或者一个更通用的解决方案,使用非常有用的组合find | xargs:

find [path] -type f -not -name 'EXPR' -print0 | xargs -0 rm --

例如,删除当前目录下的所有非txt文件:

find . -type f -not -name '*txt' -print0 | xargs -0 rm --

如果需要删除的文件名中有空格,则需要print0和-0组合。

rm !(textfile.txt|backup.tar.gz|script.php|database.sql|info.txt)

extglob(扩展模式匹配)需要在BASH中启用(如果它没有启用):

shopt -s extglob

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

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