user1081491
user1081491

Reputation: 15

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

Upvotes: 1

Views: 3392

Answers (3)

Dorian Grv
Dorian Grv

Reputation: 499

Another version, that is renaming and moving the files to the parent directory. But you can change the last line as you want.

here=$(pwd)
for f in */*.jpg; do
    dir=$(dirname $f)
    image=$(basename $f)
    echo mv ${here}/${f} ${here}/${dir}_${image}
done

Upvotes: 0

Freddy
Freddy

Reputation: 4688

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.

Upvotes: 1

Samisa
Samisa

Reputation: 1082

Try the following in your for loop. Note that '' is used to that the script can deal with spaces in the file names.

for image in "$search_dir"*.JPG
do
    echo mv "'$image'" "'${dir} ${image}'"
done

Upvotes: 1

Related Questions