3 # Rename JPEGs to reflect the creation date stored in their metadata.
5 # Copyright (C) 2010-2012 W. Trevor King <wking@tremily.us>
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with this program; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 # usage: name-by-date.sh $(find . -name '*.jpg')
24 # check for required utilities
25 DIRNAME=$(which dirname) || exit 1
26 EXIF=$(which exif) || exit 1
27 FILE_=$(which file) || exit 1
28 GREP=$(which grep) || exit 1
29 MV=$(which mv) || exit 1
30 SED=$(which sed) || exit 1
31 TEST=$(which '[') || exit 1 # but I just use [ in the script
33 NAME_BY_DATE_FIELD_NAME="${NAME_BY_DATE_FIELD_NAME:-Date and Time (Original)}"
37 TYPE=$("${FILE_}" "$FILE" | "${GREP}" JPEG)
38 if [ -n "$TYPE" ]; then
39 FIELD_NAME="$NAME_BY_DATE_FIELD_NAME"
40 if [ -z "$FIELD_NAME" ]; then
41 FIELD_NAME='Date and Time'
43 ASCII_DATE=$("${EXIF}" -m -t "$FIELD_NAME" "$FILE") # 2010:07:02 08:36:20
44 if [ $? -ne 0 ]; then # use similar field, e.g. 'Date and Time (original)'
45 FIELD=$("${EXIF}" -m "$FILE" | "${GREP}" "$FIELD_NAME" | head -n1)
46 FIELD_NAME=$(echo "$FIELD" | "${SED}" 's/\t.*//')
47 if [ -z "$FIELD_NAME" ]; then
48 echo "$FILE has no stored date"
51 echo "$FILE using date from $FIELD_NAME"
52 ASCII_DATE=$("${EXIF}" -m -t "$FIELD_NAME" "$FILE") # 2010:07:02 08:36:20
55 DATE=$(echo "$ASCII_DATE" | "${SED}" 's/:/./g' | "${SED}" 's/ /./g')
56 if [ -z "$DATE" ]; then
57 echo "$FILE has no stored date"
59 echo "$FILE taken on \"$DATE\""
60 FILE_DIR=$("${DIRNAME}" "$FILE")
61 NEW_NAME="$FILE_DIR/$DATE.jpg"
62 if [ -e "$NEW_NAME" ] && [ "$NEW_NAME" != "$FILE" ]; then
64 NEW_NAME="$FILE_DIR/${DATE}_$i.jpg"
65 while [ -e "$NEW_NAME" ] && [ "$NEW_NAME" != "$FILE" ]; do
66 echo "File \"$NEW_NAME\" already exists!"
67 NEW_NAME="$FILE_DIR/${DATE}_$i.jpg"
71 if [ "$NEW_NAME" != "$FILE" ]; then
72 "${MV}" "$FILE" "$NEW_NAME"
74 NEW_BASE="${NEW_NAME%.*}"
75 for AUXILIARY in "${BASE}"*; do
76 if [ "${AUXILIARY}" != "${BASE}*" ]; then
77 EXTENSION="${AUXILIARY:${#BASE}}"
78 NEW_AUXILIARY="${NEW_BASE}${EXTENSION}"
79 echo "Auxiliary file ${AUXILIARY} -> ${NEW_AUXILIARY}"
80 "${MV}" "${AUXILIARY}" "${NEW_AUXILIARY}"