简体   繁体   English

Bash 脚本 - 使用正则表达式循环目录

[英]Bash script - Loop through directory with regex

I'm sure this must be possible, but I'm not sure how.我确信这一定是可能的,但我不确定如何。 What I'm trying to do is loop through a directory, looking for numeric directories within, and get their disk space.我要做的是遍历一个目录,在其中寻找数字目录,并获取它们的磁盘空间。 This is what I've come up with, but it's not dealing with the regex.这是我想出的,但它不处理正则表达式。

FILES="$DIR_PATH/secure/{[0-9]+}"
for f in $FILES
do
   used=`du -s $f`
   base=`basename $f`
   mysql --user=$DB_USER --password=$DB_PASS --host=$DB_HOST $DB_NAME << EOF
       INSERT INTO disk_usage(site_id, filesystem, used, size) VALUES("$base", "Private Files", "$used", "$size")
EOF
done

In case it's not clear, I have a directory containing a bunch of directories with numeric names.如果不清楚,我有一个目录,其中包含一堆带有数字名称的目录。 This directory also contains some other files/directories that I don't want to calculate disk space on.该目录还包含一些我不想计算磁盘空间的其他文件/目录。 So I just want to loop through the directory and get the disk space used by each numeric subdirectory.所以我只想遍历目录并获取每个数字子目录使用的磁盘空间。 I'm sure this isn't optimal code, but it's being run privately on a safe filesystem, so the risk of problems is pretty low, but if there is a way to improve it, please let me know.我确信这不是最佳代码,但它是在安全的文件系统上私下运行的,所以出现问题的风险非常低,但如果有办法改进它,请告诉我。

Using bash's extended patterns使用 bash 的扩展模式

shopt -s extglob
for subdir in "$DIR_PATH"/secure/+([[:digit:]])/
# ...............................^^-----------^
...

Note the trailing slash: that limits the results to directories only, ignoring files named with all digits.请注意尾部的斜杠:它将结果限制为仅目录,忽略以所有数字命名的文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM