The Schworak Site | Log In | Up One Level

Rename image files using the EXIF date and time stamp

This little script is a simple tool to rename one or more files in a folder using the EXIF date and time stamp. Name collision is handled with a unique sequence number as needed.

#!/bin/bash
#
# rename one or more images based on the date/time exif information
#
# the "exif" program must be instale for this to work. (sudo apt-get install exif)
#
copy=0
help=0
count=0
err=0
exif=0
for file in $@; do
    if [ "$file" == "--copy" ]; then
        copy=1
    elif [ "$file" == "--help" ]; then
        help=1
    elif [ -f "$file" ]; then
        count=`expr 1 + $count`
        time=`exif --tag="Date and Time" "$file" | grep -o '[0-9][0-9][0-9][0-9]:[0-9][0-9].*[0-9][0-9]:[0-9][0-9]:[0-9][0-9]'`
        if [ "$time" != "" ]; then
            exif=`expr 1 + $exif`
        fi
    elif [ -d "$file" ]; then
        # ignore this one
        count=$count
    fi
done
if [ $help == 1 ]; then
    if [ $err > 0 ]; then
        echo ""
        echo ""
        echo ""
        echo "Errors were encountered"
    fi
    echo ""
    echo ""
    echo ""
    echo "Usage: [option] file_pattern"
    echo "/c or --copy        Copy the file(s) rather than renaming the file(s)"
    echo ""
    exit 99
fi

clear
echo "File Count: $count"
echo "EXIF Count: $exif"

for file in $@; do
    if [ -f "$file" ]; then
        time=`exif --tag="Date and Time" "$file" | grep -o '[0-9][0-9][0-9][0-9]:[0-9][0-9].*[0-9][0-9]:[0-9][0-9]:[0-9][0-9]'`
        if [ "$time" != "" ]; then
            base=$(printf "$time" | sed -r "s/[^0-9:\s]+/_/g")
            base=$(printf "$base" | sed -r "s/[^0-9_]+/-/g")
            filename=$(basename "$file")
            extension="${filename##*.}"
            extension=${extension,,} # convert to lower case
            tick=1
            pad=$(printf "%03d" $tick)
            newname=$(printf "$file" | sed -r "s/$filename\$/$base\_$pad\.$extension/g")
            while [ -f "$newname" ]; do
                tick=`expr 1 + $tick`
                pad=$(printf "%03d" $tick)
                newname=$(printf "$file" | sed -r "s/$filename\$/$base\_$pad\.$extension/g")
            done
            newfilename=$(basename "$newname")
            echo "$filename -> $time -> $newfilename"
            cp "$file" "$newname"
            if [ $copy == 0 ]; then
                rm "$file"
            fi
        fi
    fi
done

Comments

All content on this site is copyright ©2004-2019 and is not to be reproduced without prior permission.