Shell script to rename jpeg files with exif date

Script takes existing jpeg images, extracts exif date, constructs a new file name YYYY-MM-DD_HH-MM-SS.currentname, then sorts into subfolders based on year and month (YYYY-MM).

#!/bin/bash

# Script takes existing jpeg images, extracts exif date, 
# constructs a new file name YYYY-MM-DD_HH-MM-SS.currentname. 
# Then sorts into folders based on year and month (YYYY-MM).

# Expects source dir as $1
# Requires exiftags

ddir="date2file"
tmp="/tmp/date2file.tmp"

# error handling
function err_exit { echo -e 1>&2; exit 1; }

# Confirm one arguments was passed
if [ $# -ne 1 ]; then
  echo -e 1>&2 "\n Usage error! Expecting source directory as an argument. Dir can be '.', if you'd like to process all files in current dir.\n Example: $0 myfiles\n"
  exit 1
fi

# check if exiftags is a valid command
if ! which exiftags &> /dev/null; then 
  echo "Error: exiftags not found"
  exit 1
fi

# Create file list
find $1 -type f -iregex ".*\.jpe?g" > $tmp || err_exit

# Output some info
c1=$(wc -l < $tmp)
echo ""
echo " Found $c1 files to process. For list, see $tmp"
read -p " Press any key to proceed or Ctrl+C to abort.."

# Create output dir
if ! [ -d "$ddir" ]; then
  mkdir -p "$ddir" || err_exit
fi

# Process images
cat $tmp | while read f; do
  echo processing "$f"..
  imgdate=$(exiftags -s'|' "$f" | grep "^Image Created" | cut -d'|' -f2 | sed 's/:/-/g;s/ /_/;')
  newf=$(basename "$f" | sed 's/ /_/g')
  ddir1=$(echo $imgdate | awk -F'-' '{print$1"-"$2}')
    if ! [ -d "$ddir1" ]; then
      mkdir -p "$ddir/$ddir1" || err_exit
    fi
  echo "new file: $ddir/$ddir1/$imgdate.$newf"
  cp "$f" "$ddir/$ddir1/$imgdate.$newf" || err_exit
done

exit 0

2 Comments

  • 1. Alain Kelder is a Giant D&hellip replies at 29th August 2010, 8:58 pm :

    […] so I go through the trouble to write a script, to solve a problem which has already been solved. Still a fun exercise, if not exactly […]

  • 2. Marcio replies at 25th February 2013, 6:21 pm :

    Good!!! good job!!

    Thankssa

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).