Chilly Chilly - 1 month ago 8
Bash Question

Rename files numerically in place, multiple folders

I am able to rename files numerically, in place, in multiple folders. However, it is not the result I am looking for. My file structure looks as follows:

Pictures-
Vacation-
img.001.jpg
img.002.jpg
img.003.jpg
Holidays-
img.004.jpg
img.005.jpg
img.006.jpg
Fun-
img.007.jpg


What I'd like to achieve is:

Pictures-
Vacation-
img.001.jpg
img.002.jpg
img.003.jpg
Holidays-
img.001.jpg
img.002.jpg
img.003.jpg
Fun-
img.001.jpg


So far I have come up with the following:

a=1
for i in $vm/Holiday/*; do
new=$(printf "%03d.jpg" ${a})
mv ${i} $vm/Holiday/${new}
let a=a+1
done


How can I achieve my desired result without having to separately run this on every single directory within my pictures folder?

Answer

Take your version and make it iterate over the folders as well.

#!/bin/bash

for dir in ~/code/stack/Pictures/*; do
        [ -d "${dir}" ] || continue
        i=1
        for img in "${dir}"/*.jpg; do
                [ -e "${img}" ] || break
                new="$(printf "%03d.jpg" "${i}")"
                echo mv "${img}" "$(dirname "${img}")/${new}"
                ((i++))
        done
done

Change the location of your Pictures folder and dryrun with the echo in place first. Is that what you wanted...?