[译]如何从文件夹中删除所有文件,仅保留特殊的文件?

原文来源:
https://stackoverflow.com/questions/4325216/remove-all-files-except-some-from-a-directory

使用 sudo rm -r能够删除所有的文件,但是我想保留以下几个文件:

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

我该怎么做?

添加不需要删除的文件名,在 -not -name 后面

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

如果你不想一一列举不想删除的所有文件,你可以使用更为通用的方法----使用正则表达式

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

具体如下:
比方说,我想删除当前文件夹下所有不是txt的文件

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

print0 和 -0 参数是需要的,如果想要删除掉这些文件占用的空间的话。

原文地址:https://www.cnblogs.com/everfight/p/delete_except_some_file.html