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



rename to :


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

for i in *.jpg; do
  new=$(printf "%04d" ${a}) #04 pad to length of 4
  mv "${i}" ""$1"_${new}.jpg"
  let a=a+1

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' -- {} \;
  • this is worked , but old file name still exist : images/images_06_DSC00689_1_.jpg – juicebyah Dec 23 '14 at 5:09
  • @juicebyah my bad, I overlooked an important detail in your question. Fixed it now, see my updated post. – janos Dec 23 '14 at 6:06
  • 1
    nice on janos , work like a charm , thanks a lot for your effort :D – juicebyah Dec 23 '14 at 6:30

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


find parentdir -type d | while read d ; do
    # 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

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.

  • i got this error images/*.jpg': No such file or directory when executing command above – juicebyah Dec 23 '14 at 5:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.