使用sudo rm -r时,如何删除除以下文件外的所有文件?
textfile.txt
backup.tar.gz
script.php
database.sql
info.txt
使用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;
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