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

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

当前回答

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

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

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

chattr -i *

其他回答

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

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

我更喜欢使用子查询列表:

rm -r `ls | grep -v "textfile.txt\|backup.tar.gz\|script.php\|database.sql\|info.txt"`

-v,——invert-match选择不匹配的行 \ |分隔符

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

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

我相信你可以使用

rm -v !(filename)

除了文件名,所有其他文件将删除在该目录中,并确保您正在使用它

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组合。