在Linuxterminal中,如何删除一个或两个文件夹以外的所有文件?
例如。
我有一个目录中的100个图像文件和一个.txt
文件。 我想删除除.txt
文件以外的所有文件。
从目录中,列出文件,过滤掉所有不包含“文件保留”的文件,并删除列表中剩下的所有文件。
ls | grep -v 'file-to-keep' | xargs rm
为了避免文件名空间的问题(记住永远不要在文件名中使用空格),使用find
和-0
选项。
find 'path' -maxdepth 1 -not -name 'file-to-keep' -print0 | xargs -0 rm
或者混合两者,使用grep
选项-z
来管理-print0
名称
一般来说,使用grep进行倒排模式搜索应该能够完成这项工作。 由于您没有定义任何模式,我只是给你一个通用的代码示例:
ls -1 | grep -v 'name_of_file_to_keep.txt' | xargs rm -f
ls -1
1每行列出一个文件,以便grep可以逐行搜索。 grep -v
是倒转的标志。 所以任何匹配的模式都不会被删除。
对于多个文件,你可以使用egrep:
ls -1 | grep -E -v 'not_file1.txt|not_file2.txt' | xargs rm -f
问题更新后更新:我假设你愿意删除当前文件夹中不以.txt
结尾的文件。 所以这也应该工作:
find . -maxdepth 1 -type f -not -name "*.txt" -exec rm -f {} \;
找到支持一个-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
使用not
修饰符移除not
删除的file(s)
或pattern(s)
,可以修改传递给-maxdepth
的1
以指定要从中删除多少个子目录
find . -maxdepth 1 -not -name "*.txt" -exec rm -f {} \;
你也可以这样做:
find -maxdepth 1 \! -name "*.txt" -exec rm -f {} \;
在bash中,你可以使用:
$ shopt -s extglob # Enable extended pattern matching features $ rm !(*.txt) # Delete all files except .txt files