6

How to rename all files in all sub directories, with the sub directories name and auto number.

ex:

parent
-subdir
--file.jpg
--cat.jpg
--dog.jpg

rename to :

parent
-subdir
--subdir_01.jpg
--subdir_02.jpg
--subdir_03.jpg

I'm using this script but it's not recursive

#!/bin/bash
a=1
b="$1"
for i in *.jpg; do
  new=$(printf "%04d" ${a}) #04 pad to length of 4
  mv "${i}" ""$1"_${new}.jpg"
  let a=a+1
done
Braiam
  • 35,991
juicebyah
  • 379
  • 6
  • 14

2 Answers2

2

This one-liner will do it:

find path/ -name '*.jpg' -exec bash -c 'dn=$(dirname "$1"); bn=$(basename "$dn"); c=$(ls "$dn/$bn"_??.jpg 2>/dev/null | wc -l); c=$((c+1)); cnt=$(printf "%02d" $c); mv "$1" "$dn/${bn}"_$cnt.jpg' -- {} \;

With the line broken up for easier reading:

find path/ -name '*.jpg' -exec bash -c '\
  dn=$(dirname "$1"); bn=$(basename "$dn"); \
  c=$(ls "$dn/$bn"_??.jpg 2>/dev/null | wc -l); c=$((c+1)); \
  cnt=$(printf "%02d" $c); mv "$1" "$dn/${bn}"_$cnt.jpg' -- {} \;
janos
  • 11,341
0

I would recommend an iterative approach over a recursive one. To scan for (sub)directories, use the 'find' tool and its argument '-type d'.

Example:

find parentdir -type d | while read d ; do
    a=1
    # For example, $d could be "parent/subdir"
    b="$(basename $d)"
    # For above example, $b would be "subdir"
    for i in "${d}/*.jpg" ; do
        new=$(printf "%04d" ${a})
        mv "${i}" "${d}/${b}_${new}.jpg"
        let a=a+1
    done
done

I haven't tested the code yet, but it should give you a good idea how it should look like. Potential problems may be spaces in filenames; redefining IFS may help you.

f15h
  • 174