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

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

当前回答

我相信你可以使用

rm -v !(filename)

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

其他回答

不要直接执行命令,请将所需文件移动到当前目录之外的临时目录。然后使用rm *或rm -r *删除所有文件。

然后移动所需的文件到当前目录。

只是:

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

Or:

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

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

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

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

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

删除除file.name以外的所有内容:

ls -d /path/to/your/files/* |grep -v file.name|xargs rm -rf