[英]How can I delete directories based on their numeric name value with a shell script?
I have a directory that contains numerically named subdirectories ( eg. 1, 2, 3, 32000, 43546 ). 我有一个目录,其中包含以数字命名的子目录(例如1、2、3、32000、43546)。 I need to delete all directories over a certain number.
我需要删除超过一定数量的所有目录。 For example, I need to delete all subdirectories that have a name that is numerically larger than 14234. Can this be done with a single command line action?
例如,我需要删除名称在数字上大于14234的所有子目录。可以通过单个命令行操作来完成此操作吗?
rm -r /directory/subdirectories_over_14234 ( how can I do this? )
Well you can do a bash for loop instruction so as to iterate over the directory filename and use the test command then after extracting the target number of the file name. 好了,您可以执行bash for loop指令,以便遍历目录文件名并在提取文件名的目标编号之后使用test命令。
Should be something like this : 应该是这样的:
for $file in /your/path
do
#extract number here with any text processing command (ed ?)
if test [$name -leq your_value]
then
rm -R $file
fi
done
In bash, I'd write 用bash,我会写
for dir in *; do [[ -d $dir ]] && (( dir > 14234 )) && echo rm -r $dir; done
Remove the echo
at your discretion. 您可以自行决定删除
echo
。
You don't mention which shell you're using. 您没有提到正在使用哪个shell。 I'm using Zsh and it has a very cool feature: it can select files based on numbers just like you want!
我正在使用Zsh ,它具有一个非常酷的功能:它可以根据需要选择基于数字的文件! So you can do
所以你可以做
$ rm -r /directory/<14234->(/)
to select all the subdirectories of /directory
with a numeric value over 14234. 选择
/directory
所有子目录,其数字值超过14234。
In general, you use 通常,您使用
<a-b>
to select paths with a numeric values between a
and b
. 选择数字值在
a
和b
之间a
路径。 You append a (/)
to only match directories . 您追加
(/)
仅匹配目录 。 Use (.)
to only match files . 使用
(.)
仅匹配文件 。 The glob patterns in Zsh are very powerful and can mostly (if not always) replace the good old find
command. Zsh中的glob模式非常强大,可以(如果不是总是)替换掉旧的
find
命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.