在BASH中动态分配包含数字的变量

时间:2015-04-10 11:30:51

标签: bash shell dynamically-generated

我有很多文件以系统的方式分散在300个目录中:

GA001/curve_1/pdbs/FILES
GA002/curve_1/pdbs/FILES
....
GA300/curve_1/pdbs/FILES

现在我需要将所有FILES移动到名为allPDB的同一文件夹中。而不是手动做我尝试写一个bash脚本,但我显然非常无能。我试图创建一个从1到300的循环,它更新文件所在的路径,但它不起作用。我的代码如下所示

#!/bin/bash

# loop running over the 300 dirs
for i in $(seq 1 300); do
        if $i<10; then
        printf -v mypath 'GA00%s/curve_1/pdbs' $i
        elif $i=>10  && $i<100; then
        mypath=$(printf 'GA0%s/curve_1/pdbs' $i)
        else
        mypath=$(printf 'GA%d/curve_1/pdbs' $i) 
        fi

echo $mypath # used to check the generated path
cp -pr $mypath/*.pdb allPDB/

done

我已尝试根据此线程SPRINTF in shell scripting?使用PRINTF的不同实现。我也尝试在PRINTF调用中同时使用%i,%s和%d,但是为i = 9生成的路径是&#34; GA9&#34;而不是&#34; GA009&#34;。此外,我收到错误消息:

MovePDB.sh: line 5: 1: command not found
MovePDB.sh: line 7: 1=: command not found
GA1/curve_1/pdbs
cp: GA1/curve_1/pdbs/*.pdb: No such file or directory
MovePDB.sh: line 5: 2: command not found
MovePDB.sh: line 7: 2=: command not found
GA2/curve_1/pdbs
...
cp: GA98/curve_1/pdbs/*.pdb: No such file or directory
MovePDB.sh: line 5: 99: command not found
MovePDB.sh: line 7: 99=: command not found
GA99/curve_1/pdbs
cp: GA99/curve_1/pdbs/*.pdb: No such file or directory
MovePDB.sh: line 5: 100: command not found
MovePDB.sh: line 7: 100=: command not found
GA100/curve_1/pdbs
MovePDB.sh: line 5: 101: command not found
MovePDB.sh: line 7: 101=: command not found
GA101/curve_1/pdbs
MovePDB.sh: line 5: 102: command not found
MovePDB.sh: line 7: 102=: command not found

任何人都可以帮助我吗?我不明白找不到&#34; NUMBER(=)命令&#34;错误

干杯!

1 个答案:

答案 0 :(得分:3)

%03d是您需要的格式:

for i in {1..300} ; do
    printf 'GA%03d/curve_1/pdbs/\n' $i
done

为什么你不能

cp GA*/curve_1/pdbs/* allPDB/