Skip to content

Instantly share code, notes, and snippets.

@a2nt
Last active March 1, 2018 07:45
Show Gist options
  • Save a2nt/e0372ccb858825dc2bc584db41e8b921 to your computer and use it in GitHub Desktop.
Save a2nt/e0372ccb858825dc2bc584db41e8b921 to your computer and use it in GitHub Desktop.
Categorizing images by EXIF date or by file creation date if EXIF is missing
#!/usr/bin/env bash
SOURCE_DIR="${HOME}/Pictures/Photos/DCIM_SYNCED"
DEST_DIR="${HOME}/Pictures/Photos/Archived"
echo "Categorizing files from ${SOURCE_DIR} to ${DEST_DIR} ..."
## Find files and categorize them
find "${SOURCE_DIR}" -type f -regex ".*/.*\.\(jpg\|JPG\|jpeg\|JPEG\|png\|PNG\)" |
while IFS= read -r file; do
subDir=""
## Read exif date
exifDate=`exiftool -CreateDate "${file}" | grep -oP "([0-9]{4}):([0-9]{2}):([0-9]{2})"`
year="$(echo ${exifDate} | cut -f1 -d:)"
month="$(echo ${exifDate} | cut -f2 -d:)"
day="$(echo ${exifDate} | cut -f3 -d:)"
## Read file created date if there's no exif
if [ -z "${exifDate}" ]; then
echo "Exif is missing: ${file}"
year="$(date -d "$(stat -c %y "${file}")" +%Y)"
month="$(date -d "$(stat -c %y "${file}")" +%m)"
day="$(date -d "$(stat -c %y "${file}")" +%d)"
subDir="/no-exif"
fi
dirArhived="${DEST_DIR}${subDir}/${year}/${month}.${day}"
## Replace spaces and lowercase file names
newFile=$(basename "${file}" | sed 's/ /-/g' | awk '{print tolower($0)}')
## Create the directories if they don't exist. The -p flag
## makes 'mkdir' create the parent directories as needed so
## you don't need to create $year explicitly.
[[ ! -d "${dirArhived}" ]] && mkdir -p "${dirArhived}";
## Move the file
mv "${file}" "${dirArhived}/${newFile}"
echo "moved: ${file} to ${dirArhived}/${newFile}"
done
## Remove empty dirs and files
find "${SOURCE_DIR}" -empty -delete
find "${DEST_DIR}" -empty -delete
echo "... Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment