Search code examples
bashbatch-rename

Bash script for renaming files to consecutive numbers in multiple directories


I have a catalogue structure like this:

AD
 -> AD01
   -> DSC123.jpg
   -> DSC124.jpg
 -> AD02
   -> DSC234.jpg
   -> DSC1455.jpg
 -> AD03
  ->...
 -> AD04
  ->...
 ->...
AE
 ->...
...

No I would like to run a script that will traverse whole tree and rename each folder files to be a consecutive numbers 01.jpg, 02.jpg... etc.

I found something like this to help with consecutive numbers:

find -name '*.jpg' | gawk 'BEGIN{ a=1 }{ printf "mv %s %02d.jpg\n", $0, a++ }' | bash 

but how do I make it run on all the folders recursively, throughout the tree (there are like 1000 of folders each with about 6-20 files).

Edit: Result should look like this:

AD
 -> AD01
   -> 01.jpg
   -> 02.jpg
 -> AD02
   -> 01.jpg
   -> 02.jpg
 -> AD03
  ->...
 -> AD04
  ->...
 ->...
AE
 ->...
...

Solution

  • You can try this bash script,

    #!/bin/bash
    for dir in $(find -type d \( ! -name '.*' \)) 
    do 
      i=1; 
      for file in $(find "$dir" -name '*.png')
      do 
         a=$(printf "%02d" $i)
         new=${file%/*}
         echo "mv $file $new/$a.png"
         let i=i+1
      done 
    done
    

    It will list out the mv commands that is going to apply. See whether it is giving what you expected. Finally, replace the echo with mv command.