1

I have several folders within a parent folder, which all have the structure below, and am struggling to create a specific loop.

parentfolder/folder01/subfolder/map.png
parentfolder/folder02/subfolder/map.png
parentfolder/folder03/subfolder/map.png
parentfolder/folder04/subfolder/map.png

etc...

so each subfolder contains a file called map.png (i.e. same filename in all subfolders, but they are different files).

I would like to copy each map.png file and place it into the overall Parentfolder, but at the same time I want the copy to be renamed based on the Folder above 'subfolder'.

So for example, I want to copy map.png from parentfolder/folder01/subfolder to parentfolder whilst renaming it folder01.png (and for this then to be done accordingly for all others, using a loop).

I have tried something along these lines but am obviously sruggling to get it to do what I want it to:

for i in parentfolder/*; do 
  cd $i
  cd subfolder
  cp map.png ../../"$i".png
  cd -
done

I am still a beginner and very new to this so would appreciate any help. Thanks so much.

2

You may try something like the following for loop,

for d in parentfolder/* ; do
    cp "$d/subfolder/map.png" "$d.png"
done

You should run it when your current directory is on the same level of the parentfolder.

0
0

Zsh comes with a utility zmv which is good for pattern-based renaming and copying of files. Put this in your .zshrc if you don't already have it:

autoload -U zmv
alias zcp='zmv -C'
alias zln='zmv -L'

(Or run these commands in your shell session to enable them just for this session.)

Then (from parentfolder):

zcp '(*)/subfolder/map.png' '$1.png'

The first argument is the pattern to replace. The second argument is the replacement name. In the replacement, $1, $2 and so on refer to the corresponding parenthesized group in the pattern. See the manual for other possibilities and limitations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.