[英]In a Linux script, how to remove all files & directories but one, in current directory?
In a shell script, I want to remove all files and directories but one file, in the current directory. 在shell脚本中,我想删除当前目录中的所有文件和目录,但删除一个文件。 I used 我用了
ls | grep -v 'nameoffiletokeep' | xargs rm
this removes files, but directories are not deleted. 这将删除文件,但不会删除目录。
find . -mindepth 1 -maxdepth 1 ! -iname nameoffiletokeep -print0| xargs -0 rm -rf;
This finds all files and directories that are direct children of the current working directory that are not named nameoffiletokeep
and removes them all (recursively for directories), regardless of leading dots (eg .hidden
, which would be missed if you used a glob like rm -rf *
), spaces, or other metachars in the file names. 这个发现是未命名当前工作目录的直接孩子的所有文件和目录nameoffiletokeep
并删除它们所有(递归目录),无论领导点(如.hidden
,如果你使用的水珠像这将错过rm -rf *
),文件名中的空格或其他元字符。
I've used -iname
for case-insensitive matching against nameoffiletokeep
, but if you want case-sensitivity, you should use -name
. 我已经使用-iname
对nameoffiletokeep
进行不区分大小写的匹配,但是如果要区分大小写,则应该使用-name
。 The choice should depend on the underlying file system behavior, and your awareness of the letter-case of the file name you're trying to protect. 选择应取决于基础文件系统的行为以及您对要保护的文件名字母大小写的了解。
If you are using bash, you can use extended globbing: 如果您正在使用bash,则可以使用扩展的globbing:
shopt -s extglob
rm -fr !(nameoffiletokeep)
In zsh the same idea is possible: 在zsh中,相同的想法是可能的:
setopt extended_glob
rm -fr ^nameoffiletokeep
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.