在Linux脚本中,如何删除当前目录中除一个之外的所有文件和目录?

时间:2021-11-11 07:11:12

In a shell script, I want to remove all files and directories but one file, in the current directory. I used

在shell脚本中,我希望删除当前目录下的所有文件和目录。我使用

 ls | grep -v 'nameoffiletokeep' | xargs rm

this removes files, but directories are not deleted.

这将删除文件,但不会删除目录。

2 个解决方案

#1


2  

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 (e.g. .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 *),空格或其他metachars文件名。

I've used -iname for case-insensitive matching against nameoffiletokeep, but if you want case-sensitivity, you should use -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.

我已经对nameoffiletokeep使用-iname进行不区分大小写的匹配,但是如果您希望区分大小写,则应该使用-name。选择应该取决于底层文件系统行为,以及您对要保护的文件名的字母大小写的意识。

#2


1  

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

#1


2  

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 (e.g. .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 *),空格或其他metachars文件名。

I've used -iname for case-insensitive matching against nameoffiletokeep, but if you want case-sensitivity, you should use -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.

我已经对nameoffiletokeep使用-iname进行不区分大小写的匹配,但是如果您希望区分大小写,则应该使用-name。选择应该取决于底层文件系统行为,以及您对要保护的文件名的字母大小写的意识。

#2


1  

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