在shell脚本中迭代文件夹,例如folder0100,folder0101到folder1100

时间:2013-05-28 05:05:26

标签: bash shell scripting-language

我写了一个小的shell脚本来迭代文件夹中包含数字的文件夹。脚本如下。

#!/bin/bash
for (( i = 100; i < 1000; i++))
do
    cp test0$i/test.out executables/test0$i.out
done

这里他的脚本遍历test0100 ..到test0999。 我想增强此脚本以从 test0000 遍历到 test1100 文件夹。我无法做到这一点。

我是shell脚本新手。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:3)

使用seq:

for i in $(seq -w 0 1100); do
    cp test$i/test.out executables/test$i.out
done

使用-w标志seq pad生成带前导零的数字,使所有数字的长度相等。

答案 1 :(得分:2)

这个怎么样 -

#!/bin/bash
for (( i = 0; i < 1100; i++))
do
    cp test$(printf "%04d" $i)/test.out executables/test$(printf "%04d" $i).out
done

答案 2 :(得分:0)

最近的bash

#!/bin/bash
for i in {0000..1100}; do
do
    cp test$i/test.out executables/test$i.out
done

请注意,大括号扩展发生在变量扩展之前(参见the manual),所以如果你想做

start=0000
stop=1100
for i in {$start..$stop}

这不起作用。在这种情况下,请使用seq