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
通常,使用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)
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)