A bash script to rename images to their creation date and time.

#!/bin/bash
#
# batchrename
# Change file name(s) to timestamp, preserving
# file extension(s)
# by Vitalie Ciubotaru
# August 17, 2011
#

renameit() {
# get extension
extension=${file2rename##*.};

# check if destination file exists
new_filename=`ls -l --time-style="+%Y.%m.%d.%H.%M.%S" "$file2rename" | cut -d' ' -f6`
if [ -e "$new_filename.$extension" ]
then
echo "destination file for ${file2rename} exists. Appending extra characters"

# Appending characters
export i=1
while [ "$i" -lt 10000 ]
do
case ${#i} in
1 ) extrachar="000"$i;;
2 ) extrachar="00"$i;;
3 ) extrachar="0"$i;;
4 ) extrachar=$i;;
esac
# test if file exists
if [ -e "$new_filename$extrachar.$extension" ]
# if so then pick next extra character
then
let i=$i+1
#if not then rename and proceed to the next file
else
mv -v $file2rename $new_filename$extrachar'.'$extension
i=10000
fi
done
else

# just rename and move to the next file
mv -v "$file2rename" $new_filename'.'$extension
fi
}

# check if the filename is given
if [ -z $1 ] || [ $1 == "-help" ] || [ $1 == "-?" ]
then
echo "Usage: `basename $0` file-to-rename"
exit 1
fi

# set the counter of renamed files
export rename_counter=0

# resolve wildcards and get a list of files to rename
for file2rename in $*
do
# first, check if file exists
if [ -f "$file2rename" ]
then
renameit
let rename_counter=$rename_counter+1
else
echo "File" $file2rename "does not exist."
fi
done

# reporting results
if [ "$rename_counter" -eq "0" ]
then
echo "no files to rename"
else
echo "total: $rename_counter file(s)"
fi

Leave a Reply