#!/bin/sh USAGE='Usage: brewsort Sort image-files into new directory based on date information in EXIF-metatag. Depends on exiftool. Copyright © Daniel Ljunggren . April 2010. [options]: -s : Suffix to directory name -d : Use specific date as directory name ' SUFFIX="" DATE="" while [ $# -gt 0 ] do case "$1" in -s) SUFFIX="_$2" shift 1 ;; -d) if [[ $2 == [0-9][0-9][0-9X][0-9X][0-9X][0-9X] ]]; then DATE="$2" else echo "$USAGE" 1>&2 exit 2 fi shift 1 ;; -*) echo "$USAGE" 1>&2 exit 2 ;; *) break ;; esac shift 1 done for FILE do if [ -e "${FILE}" ]; then DIR=`dirname $FILE` BASE=`basename $FILE` if [[ -z ${DATE} ]]; then # Find the creation date for file EXIFERROR=`exiftool $FILE 2>&1 1>/dev/null | grep Error` # Redirect stdout to null and stderror to stdout # Use the file's EXIF image information if file type supported if [[ -z "$EXIFERROR" ]]; then DATE_YY=`exiftool -p '$DateTimeOriginal' $FILE | cut -b1-4 | sed 's/ //;s/://g'` DATE_MM=`exiftool -p '$DateTimeOriginal' $FILE | cut -b6-7 | sed 's/ //;s/://g'` fi # Use the file's date in filename if above information failed if [ -z $DATE_YY ] || [ -z $DATE_MM ]; then DATE_YY_short=`expr "$BASE" : '.*[A-Z]\([0-9][0-9]\)[0-9][0-9][0-9][0-9].*$'` DATE_YY=20"$DATE_YY_short" DATE_MM=`expr "$BASE" : '.*[A-Z][0-9][0-9]\([0-9][0-9]\)[0-9][0-9].*$'` echo "brewsort: Warning: Using the file's date in filename to sort $FILE" fi # Use the file's date-stamp if above information failed if [ -z $DATE_YY ] || [ -z $DATE_MM ]; then #DATE=`date -r "$FILE" +%y%m%d` DATE_YY=`date -r "$FILE" +"%Y"` DATE_MM=`date -r "$FILE" +"%m"` echo "brewsort: Warning: Using the file's date-stamp to sort $FILE" fi else DATE_YY_short=`expr "${DATE}" : '.*\([0-9][0-9]\)[0-9][0-9][0-9X][0-9X].*$'` DATE_YY=20"$DATE_YY_short" DATE_MM=`expr "${DATE}" : '.*[0-9][0-9]\([0-9][0-9]\)[0-9X][0-9X].*$'` echo "brewsort: Warning: Using the specified date ${DATE} to sort $FILE" fi # Create new catalog if it doesn't exist NEWDIR=${DATE_YY}\_${DATE_MM}${SUFFIX} #mkdir -p "${DIR}/${NEWDIR}" mkdir -p "${NEWDIR}" #NEWFILE="${DIR}/${NEWDIR}/${BASE}" NEWFILE="${NEWDIR}/${BASE}" # Rename file if [ ! -e "${NEWFILE}" ]; then mv "${FILE}" "${NEWFILE}" chmod 644 "${NEWFILE}" echo "brewsort: ${NEWFILE} created..." else echo "brewsort: Warning: ${NEWFILE} already exist, skipping..." fi else echo "brewsort: Warning: ${FILE} does not exist, skipping..." fi done