在Linux终端中,如何删除目录中除一个或两个以外的所有文件

Bil*_*lal 14 linux filesystems shell ubuntu

在Linux终端中,如何从一个或两个文件夹中删除所有文件?

例如.

我在一个目录和一个文件中有100个图像.txt文件.我想删除除该.txt文件以外的所有文件.

Did*_*set 31

在目录中,列出文件,过滤掉所有不包含'file-to-keep'的文件,并删除列表中剩余的所有文件.

ls | grep -v 'file-to-keep' | xargs rm
Run Code Online (Sandbox Code Playgroud)

为避免文件名中的空格问题(请记住永远不要在文件名中使用空格),请使用find-0选项.

find 'path' -maxdepth 1 -not -name 'file-to-keep' -print0 | xargs -0 rm
Run Code Online (Sandbox Code Playgroud)

或者混合两者,使用grep选项-z来管理-print0名称find


Con*_*Map 8

通常,使用grep的反向模式搜索应该可以完成这项工作.由于您没有定义任何模式,我只是给您一个通用的代码示例:

ls -1 | grep -v 'name_of_file_to_keep.txt' | xargs rm -f
Run Code Online (Sandbox Code Playgroud)

ls -1列表每行一个文件,这样的grep可以通过网上搜索线.grep -v是倒旗.因此,任何匹配的模式都不会被删除.

对于多个文件,您可以使用egrep:

ls -1 | grep -E -v 'not_file1.txt|not_file2.txt' | xargs rm -f
Run Code Online (Sandbox Code Playgroud)

问题更新后更新: 我假设您愿意删除除当前文件夹中未结束的文件以外的所有文件.txt.所以这也应该有效:

find . -maxdepth 1 -type f -not -name "*.txt" -exec rm -f {} \;
Run Code Online (Sandbox Code Playgroud)


Jos*_*h J 5

find 支持一个-delete选项,所以你不需要-exec。您还可以通过多组-not -name somefile -not -name otherfile

user@host$ ls
1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt josh.pdf keepme

user@host$ find . -maxdepth 1 -type f -not -name keepme -not -name 8.txt -delete

user@host$ ls
8.txt  keepme
Run Code Online (Sandbox Code Playgroud)