Skip to content

Instantly share code, notes, and snippets.

@schdav
Last active June 23, 2024 19:32
Show Gist options
  • Save schdav/36cb9409f0e8225c2712fed472b316ff to your computer and use it in GitHub Desktop.
Save schdav/36cb9409f0e8225c2712fed472b316ff to your computer and use it in GitHub Desktop.
Rename Photos Script
#! /bin/bash
# rphoto.sh - rename photos script
#
# Requirements:
# ExifTool (https://exiftool.org/)
#
# Usage:
# $1 = folder
# $2 = name
#
# Example:
# ./rphoto.sh Mallorca/ Mallorca
#
# Output:
# <name>_<counter>_<date>
#
# Info:
# Counter has leading zeros up to 1000 files.
# Date format is YYYYMMDD.
# Only jpeg and mov files are considered.
#
# Disclaimer:
# This script only works for some specific uses cases
# and it's not very fast at processing large amounts of files.
# The code is also not perfect and can certainly be improved.
# I just needed a tool to easily rename my vacation photos
# and didn't want to buy an overpriced app for macOS.
counter=1
files=()
length=0
types=("*.jpeg" "*.mov")
cd "$1"
# Set internal field separator to newline.
IFS=$'\n'
echo "Calculating..."
for file in ${types[@]}; do
if [ -f "$file" ]; then
# Rename file to avoid name conflicts.
mv "$file" "$file.bak"
# Store file in array.
files+=("$file")
fi
done
# Sort array.
sfiles=($(sort <<<"${files[*]}"))
# Get length of array.
length="${#sfiles[@]}"
echo "${length} files found."
# Calculate leading zeros.
if [ ${#sfiles[@]} -gt 999 ]; then
format="%04g"
else
format="%03g"
fi
for file in ${sfiles[@]}; do
# Assign formatted counter.
printf -v fcounter "${format}" $counter
if [ "${file##*.}" == "jpeg" ]; then
cdate=$(exiftool -s3 -CreateDate -d "%Y%m%d" "$file.bak")
else
cdate=$(exiftool -s3 -CreationDate -d "%Y%m%d" "$file.bak")
fi
mv "$file.bak" "$2_${fcounter}_${cdate}.${file##*.}"
echo "Renamed ${counter}/${length} files."
((counter++))
done
echo "Done."
# Reset internal field separator.
unset IFS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment