#!/bin/bash # # Rename JPEGs to reflect the creation date stored in their metadata. # # Copyright (C) 2010-2011 W. Trevor King # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # # usage: name-by-date.sh $(find . -name '*.jpg') # check for required utilities DIRNAME=$(which dirname) || exit 1 EXIF=$(which exif) || exit 1 FILE_=$(which file) || exit 1 GREP=$(which grep) || exit 1 MV=$(which mv) || exit 1 SED=$(which sed) || exit 1 TEST=$(which '[') || exit 1 # but I just use [ in the script while [ -n "$1" ]; do FILE=$1 TYPE=$("${FILE_}" "$FILE" | "${GREP}" JPEG) if [ -n "$TYPE" ]; then FIELD_NAME="$NAME_BY_DATE_FIELD_NAME" if [ -z "$FIELD_NAME" ]; then FIELD_NAME='Date and Time' fi ASCII_DATE=$("${EXIF}" -m -t "$FIELD_NAME" "$FILE") # 2010:07:02 08:36:20 if [ $? -ne 0 ]; then # use similar field, e.g. 'Date and Time (original)' FIELD=$("${EXIF}" -m "$FILE" | "${GREP}" "$FIELD_NAME" | head -n1) FIELD_NAME=$(echo "$FIELD" | "${SED}" 's/\t.*//') if [ -z "$FIELD_NAME" ]; then echo "$FILE has no stored date" ASCII_DATE="" else echo "$FILE using date from $FIELD_NAME" ASCII_DATE=$("${EXIF}" -m -t "$FIELD_NAME" "$FILE") # 2010:07:02 08:36:20 fi fi DATE=$(echo "$ASCII_DATE" | "${SED}" 's/:/./g' | "${SED}" 's/ /./g') if [ -z "$DATE" ]; then echo "$FILE has no stored date" else echo "$FILE taken on \"$DATE\"" FILE_DIR=$("${DIRNAME}" "$FILE") NEW_NAME="$FILE_DIR/$DATE.jpg" if [ -e "$NEW_NAME" ] && [ "$NEW_NAME" != "$FILE" ]; then i=1 NEW_NAME="$FILE_DIR/${DATE}_$i.jpg" while [ -e "$NEW_NAME" ] && [ "$NEW_NAME" != "$FILE" ]; do echo "File \"$NEW_NAME\" already exists!" NEW_NAME="$FILE_DIR/${DATE}_$i.jpg" let "i += 1" done fi if [ "$NEW_NAME" != "$FILE" ]; then "${MV}" "$FILE" "$NEW_NAME" fi fi fi shift done