bashmacosrenamefinder

Bash to rename files to append folder name


In folders and subfolders, I have a bunch of images named by date. I'm trying to come up with a script to look into a folder/subfolders and rename all jpg files to add the folder name.

Example:

/Desktop/Trip 1/200512 1.jpg

/Desktop/Trip 1/200512 2.jpg

would became:

/Desktop/Trip 1/Trip 1 200512 1.jpg

/Desktop/Trip 1/Trip 1 200512 2.jpg

I tried tweaking this script but I can't figure out how to get it to add the new part. I also don't know how to get it to work on subfolders.

#!/bin/bash
# Ignore case, i.e. process *.JPG and *.jpg
shopt -s nocaseglob
shopt -s nullglob

cd ~/Desktop/t/

# Get last part of directory name
here=$(pwd)
dir=${here/*\//}
i=1
for image in *.JPG 
do
   echo mv "$image" "${dir}${name}.jpg"
   ((i++))
done

Solution

  • Using find with the -iname option for a case insensitive match and a small script to loop over the images:

    find /Desktop -iname '*.jpg' -exec sh -c '
      for img; do
        parentdir=${img%/*}      # leave the parent dir (remove the last `/` and filename)
        dirname=${parentdir##*/} # leave the parent directory name (remove all parent paths `*/`)
        echo mv -i "$img" "$parentdir/$dirname ${img##*/}"
      done
    ' sh {} +
    

    This extracts the parent path for each image path (like the dirname command) and the directory name (like basename) and constructs a new output filename with the parent directory name before the image filename.

    Remove the echo if the output looks as expected.