首页 > 解决方案 > Writing a script to copy two files from each directory to each of their corresponding directories

问题描述

I have 19 directories (0, n10, n20, n30, ... n180) under the folder "mini". I need to copy two files from each directory (0_mini_vh1.coor and 0_mini_vh1.xsc, n10_mini_vh1.coor and n10_mini_vh1.xsc, so on) into their corresponding directories with the same name (0, n10, n20, so on) under the folder "production". So far, I have this written for a script, but it doesn't seem to be working. How should I improve the script?

#!/usr/bin/env bash
for f in n10  n100  n110  n120  n130  n140  n150  n160  n170  n180  n20  n30  n40  n50  n60  n70  n80  n90
do
cd $f
echo "cp $f_mini_vh1.coor ../../production/$f"
echo "cp $f_mini_vh1.xsc ../../production/$f"
cd ../
done

标签: bashshell

解决方案


for f in n{10..180..10}; do (
    cd "$f"
    echo cp "$f"_mini_vh1.{coor,xsc} ../../production/"$f"
) done

您可以使用花括号扩展为所有所需的名称:{start..stop..incr}. 您可以使用相同的技巧将两个文件名与{coor,xsc}.

小心书写$f_mini_vh1。那是一个名为 的变量f_mini_vh1。要与f其余部分分开,您需要编写${f}_mini_vh1"$f"_mini_vh1。我建议后者遵循始终引用变量扩展的一般指导。

带括号的子外壳将使您不必cd ../每次都这样做。我喜欢在任何时候cd在脚本中使用子shell 来限制目录更改的范围。

您也可以cd通过将添加传递$fcp命令来完全跳过 -ing:

for f in n{10..180..10}; do
    echo cp "$f"/"$f"_mini_vh1.{coor,xsc} ../production/"$f"
done

推荐阅读