Bash cd 进入具有增量名称的子目录

标签 bash file increment redhat cd

我在当前目录中有一个文件夹列表,名称为“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/

相关文章:

python - 为什么sfml无法在此python代码中的函数内播放文件?

java - 列出目录中的所有文件夹,即使添加新文件也不更改顺序

c - 为什么像(++(*++b))这样的东西是非法的?

javascript - 找出值是否大于或小于以前的值Javascript

java - 应用程序内 Java 命令行

linux - 按包含的字符串搜索文件并按大小排序

linux - 修改/etc/profile linux

C 线程文件系统操作 : to ftw() or to fts_open()?

objective-c - 在NSArray中增加NSNumber

bash - 从命令计数和输出行