I have a list of jpeg files in a directory like this (below is just a sample, like the structure is the same but this there are many fo0# sub-folders, not only fo01 and fo01, where each of these subfolders has many .jpeg images, not only two):

`-- main
    |-- ccc
    |   |-- fo01
    |   |   |-- ccc_fo01_c_000.jpeg
    |   |   `-- ccc_fo01_c_001.jpeg
    |   `-- fo02
    |       |-- ccc_fo02_c_000.jpeg
    |       `-- ccc_fo02_c_001.jpeg
    |-- ddd
    |   |-- fo01
    |   |   |-- ddd_fo01_d_000.jpeg
    |   |   `-- ddd_fo01_d_001.jpeg
    |   `-- fo02
    |       |-- ddd_fo02_d_000.jpeg
    |       `-- ddd_fo02_d_001.jpeg
    `-- lll
        |-- fo01
        |   |-- lll_fo01_l_000.jpeg
        |   `-- lll_fo01_l_001.jpeg
        `-- fo02
            |-- lll_fo02_l_000.jpeg
            `-- lll_fo02_l_001.jpeg

some of the renamed ccc_foo#_c_### will be manually copied to the ccc directory. What I want to do is to check these manually copied files and then copy the equivalent d_foo#_d_### and lll_foo#_l_### in the ddd and lll directories respectively. For example if I copied ccc_fo01_c_001.jpeg and ccc_fo02_c_000.jpeg to the ccc folder, then my script should copy:

  • ddd_fo01_d_001.jpeg and ddd_fo02_d_000.jpeg to the ddd
  • lll_fo01_l_001.jpeg and l_fo02_l_000.jpeg to the lll
  • The structure you describe is the desired structure or the existing structure?
    – Arcege
    Mar 12, 2015 at 23:15
  • @Arcege thanks for your comment. It is the current structure.
    – Tak
    Mar 12, 2015 at 23:15

1 Answer 1


In bash:

for x in ccc/*; do
  [ -f "$x" ] || continue                  # skip directories in ccc
  y=${x#*_}                                # strip the ccc_ prefix
  cp -p ddd/*/ddd_"${y/_c_/_d_}" ddd/      # copy the corresponding file under ddd
  cp -p lll/*/lll_"${y/_c_/_l_}" lll/      # ditto under lll

This script assumes that you don't have e.g. fo03 files in a fo01 directory, or if you do have them you want to copy them anyway. If this isn't the case you may want to adjust the filename manipulation to match your exact scenario.

You may want to investigate bash's parameter expansion features for more information.

  • thanks for your answer. I tried it but I get this error: cp: cannot stat ddd/*/ddd_fo01_l_003.png: No such file or directory the l_003 should be d_003
    – Tak
    Mar 13, 2015 at 0:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .