Search code examples
macosfor-loopterminalrenaming

Looping through folders and renaming all files in each folder sequentially with folder name


I have a series of subfolders, each with images on them.

Structure looks like

/stuff/
   IMG_012.JPG
   IMG_013.JPG
   IMG_014.JPG

/morestuff/
   IMG_022.JPG
   IMG_023.JPG
   IMG_024.JPG

I would like to write a script on my mac terminal to loop through each folder and rename the images sequentially including the folder name. So, the above structure would look like:

/stuff/
   stuff_1.JPG
   stuff_2.JPG
   stuff_3.JPG

/morestuff/
   morestuff_1.JPG
   morestuff_1.JPG
   morestuff_1.JPG

I orignally tried creating a Automator workflow and using variables, but had difficulty assigning the folder name as the variable and getting the loop to work.

I'm hoping there is an elegant solution with the terminal.

Any ideas?


Solution

  • This should work nicely for you. Save it in your HOME directory as "RenameImages", then make it executable like this:

    cd
    chmod +x RenameImages
    

    Then you can run it (-exec) it on every directory (-type d) like this:

    find . -type d -exec ./RenameImages {} \;
    

    Here is the script:

    #!/bin/bash
    # Ignore case, i.e. process *.JPG and *.jpg
    shopt -s nocaseglob
    shopt -s nullglob
    
    # Go to where the user says
    echo Processing directory $1
    cd "$1" || exit 1
    
    # Get last part of directory name
    here=$(pwd)
    dir=${here/*\//}
    i=1
    for image in *.JPG 
    do
       echo mv "$image" "${dir}${i}.jpg"
       ((i++))
    done
    

    At the moment it does nothing except show you what it would do. If you like what it is doing, simply remove the word echo from the 3rd to last line and run it again.