Script to sort JPG by metadata date

Step-by-Step descriptions of how to do things.
Post Reply
User avatar
peter_b
Chatterbox
Posts: 383
Joined: Tue Nov 12, 2013 2:05 am

Script to sort JPG by metadata date

Post by peter_b »

This small bash script sorts JPG images recovered using foremost or scalpel.
Their file timestamp is useless, since all recovered files have the current date/time.
Most cameras write the date inside the file as metadata in the form "YYYY:MM:DD".

This script sorts them into a single folder per-month:

Code: Select all

#!/bin/bash

ACTION="$1"
FILETYPE="$2"
DIR_OUT="${3:-.}"
YEAR_BEGIN="${4:-1970}"
YEAR_END="${5:-3000}" # Warning: Susceptible to Y3K bug.

case "$ACTION" in
    years)
        echo "Begin: $YEAR_BEGIN --- End: $YEAR_END"
        YEAR="$YEAR_BEGIN"
        while [ $YEAR -le $YEAR_END ]; do
            MONTH=1
            while [ $MONTH -le 12 ]; do
                TIMESTAMP=$(printf "%d-%02d\n" "$YEAR" "$MONTH")
                TIMESTRING=$(printf "%d:%02d:\n" "$YEAR" "$MONTH")

                echo ""
                echo "Timestamp: $TIMESTAMP"

                TARGET="$DIR_OUT/$TIMESTAMP"
                echo "Target: $TARGET"

                MONTH=$(($MONTH+ 1))
                mkdir "$TARGET"

                CMD="grep -l \"$TIMESTRING\" *.$FILETYPE | while read f; do mv \"\$f\" $TARGET; done"
                echo "$CMD"
                eval "$CMD"

                #Remove folder if empty:
                rmdir --ignore-fail-on-non-empty "$TARGET"
                sleep 1
            done
            YEAR=$(($YEAR + 1))
        done
    ;;

    *)
        echo ""
        echo "SYNTAX: $0 (ACTION) FILETYPE DIR_OUT YEAR_BEGIN YEAR_END"
        echo ""
        echo "Example:"
        echo "  $0 years jpg out 2014 2019"
        echo ""
        echo ""
    ;;
esac
Post Reply