我在当前目录中有一个文件夹列表,名称为“S01.result”到“S15.result”等等。我正在尝试编写一个脚本,将 cd 放入名称模式为“sXX.result”的每个文件夹,并在每个子目录中执行一些操作。
这就是我正在尝试的:
ext = ".result"
echo -n "Enter the number of your first subject."
read start
echo -n "Enter the number of your last subject. "
read end
for i in {start..end};
do
if [[i < 10]]; then
name = "s0$i&ext"
echo $name
else
name = "s$i$ext"
echo $name
fi
#src is the path of current directory
if [ -d "$src/$name" ]; then
cd "$src/$name"
#do some other things here
fi
done
我是否正确连接了文件名,是否正确找到了子目录?有没有更好的方法呢?
最佳答案
您说您需要cd
进入每个与模式匹配的文件夹,因此我们可以遍历当前目录中的所有文件/文件夹,以找到与所需模式匹配的子目录。
#!/bin/bash
# Get current working directory
src=$(pwd)
# Pattern match as you described
regex="^s[0-9]{2}\.result$"
# Everything in current directory
for dir in "$src"/*; do
# If this is a directory that matches the pattern, cd to it
# Will early terminate on non-directories
if test -d $dir && [[ $dir =~ $regex ]]; then
cd "$dir"
# Do some other things here
fi
done
关于Bash cd 进入具有增量名称的子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32404733/