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
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' -- {} \;
  • 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
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.

  • 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.