在从那里我运行bash脚本的目录,嵌套的循环在bash
目录保存在变量:
ScriptDir=`pwd`
我有以下文件:
B3LYP_BOTTOM_FRAGMENT
B3LYP-D3_BOTTOM_FRAGMENT
PBE_BOTTOM_FRAGMENT
LDA_BOTTOM_FRAGMENT
PBE-D3_BOTTOM_FRAGMENT
PBE0_BOTTOM_FRAGMENT
PBE0-DC_BOTTOM_FRAGMENT
254.186305_TOP_FRAGMENT.d12
252.050453_TOP_FRAGMENT.d12
249.921810_TOP_FRAGMENT.d12
247.812353_TOP_FRAGMENT.d12
245.699603_TOP_FRAGMENT.d12
243.644688_TOP_FRAGMENT.d12
241.581529_TOP_FRAGMENT.d12
239.554134_TOP_FRAGMENT.d12
237.467646_TOP_FRAGMENT.d12
235.473555_TOP_FRAGMENT.d12
这些文件可以分为两个不同的变量:DIRS
和FOLDERS
DIRS="
PBE-D3
PBE
B3LYP
B3LYP-D3
PBE0
PBE0-DC
LDA
"
FOLDERS="
237.467646
239.554134
241.581529
243.644688
245.699603
247.812353
249.921810
252.050453
254.186305
235.473555
"
鉴于此路径:/path/to/target
,如果我遍历DIRS
($i
)和FOLDERS
($j
),我想用下面落得:
ls -lrth /path/to/target/PBE-D3/scaling_volumes/237.467646
237.467646_TOP_FRAGMENT.d12 # j = 1 on FOLDERS
PBE-D3_BOTTOM_FRAGMENT # i = 1 on DIRS
237.467646.d12
# where `237.467646.d12` is the result of doing:
# cat 237.467646_TOP_FRAGMENT.d12 PBE-D3_BOTTOM_FRAGMENT > 237.467646.d12
ls -lrth /path/to/target/PBE-D3/scaling_volumes/239.554134
239.554134_TOP_FRAGMENT.d12 # j = 2 on FOLDERS
PBE-D3_BOTTOM_FRAGMENT # i = 1 on DIRS
239.554134.d12
ls -lrth /path/to/target/PBE-D3/scaling_volumes/241.581529
241.581529_TOP_FRAGMENT.d12 # j = 3 on FOLDERS
PBE-D3_BOTTOM_FRAGMENT # i = 1 on DIRS
241.581529.d12
# and so on...
# In other words, in this iteration, all the `j`th `FOLDERS` for a given `j`th `DIR`
# For the second `DIR`, again the 1st `FOLDER`:
ls -lrth /path/to/target/PBE/scaling_volumes/237.467646
237.467646_TOP_FRAGMENT.d12 # j = 1 on FOLDERS
PBE_BOTTOM_FRAGMENT # i = 2 on DIRS
237.467646.d12
# and so on
我写了下面的脚本:
DIRS="
PBE-D3
PBE
B3LYP
B3LYP-D3
PBE0
PBE0-DC
LDA
"
FOLDERS="
237.467646
239.554134
241.581529
243.644688
245.699603
247.812353
249.921810
252.050453
254.186305
235.473555
"
ScriptDir=`pwd`
for i in ${DIRS}; do
cd /path/to/target/$i
rm -Rf scaling_volumes
mkdir scaling_volumes
cd scaling_volumes
for j in ${FOLDERS}; do
rm -Rf ${j}
mkdir ${j}
cd $ScriptDir
cp -avr ${j}_TOP_FRAGMENT.d12 /path/to/target/$i/scaling_volumes/${j}
cp -avr ${i}_BOTTOM_FRAGMENT /path/to/target/$i/scaling_volumes/${j}
cd /path/to/target/$i/scaling_volumes/${j}
cat ${j}_TOP_FRAGMENT.d12 ${i}_BOTTOM_FRAGMENT > ${j}.d12
cd $ScriptDir
done
done
出于某种原因,我得到的是:
ls -lrth /path/to/target/PBE-D3/scaling_volumes
235.473555 # Only the last FOLDER has been created
或:
ls -lrth /path/to/target/PBE/scaling_volumes
235.473555 # Only the last FOLDER has been created
其中只有最后j
日FOLDER
创建
您在循环结束时执行'cd $ ScriptDir',下一次迭代从那里开始,但第一次迭代从'scaling_volumes'开始。 – choroba
由于您使用'bash',因此您可以使用'pushd,popd'代替'cd'来进出目录。 – iamauser
@choroba非常感谢您提供的不仅仅是有用的好建议(见答案) –