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

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

当前回答

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

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

其他回答

只是:

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

Or:

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

如果你正在使用zsh,我强烈推荐。

rm -rf ^file/folder pattern to avoid

与extended_glob

setopt extended_glob
rm -- ^*.txt
rm -- ^*.(sql|txt)
rm !(textfile.txt|backup.tar.gz|script.php|database.sql|info.txt)

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

shopt -s extglob

试着这样做:

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

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

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