Rename files with number using bash

Alec Jacobson

July 12, 2011

weblog/

I had a bunch of jpegs:
 my_file_name.jpg
 my_other_file_name.jpg
 here's_one.more.jpeg
 ...
 my_fiftieth_file.jpg
and I want to quickly rename them to
01.jpg
02.jpg
03.jpg
...
50.jpg
I do this with the following small script in bash. Save this in rename_numbered.sh:
#!/bin/bash
# USAGE: rename_numbered.sh files
x=1;
pad=`echo "(l($#+1)/l(10)) + 0.5" | bc -l`
for var in "$@"
do
  dn=`dirname $var`;
  ext=${var##*.}
  echo $ext
  echo "mv \"$var\" \"$dn/`printf '%0'$pad'd' $x`.$ext\""
#uncomment next line to enable
#  mv "$var" "$dn/`printf '%0'$pad'd' $x`.$ext"
  x=$(($x+1));
done
Then you can rename a bunch of files, like all those in a directory with:
./rename_numbered.sh path/to/dir/*