In this post I write about how it is possible rename all the photos in a folder based on the date and time information stored in the file.
I mainly take photos with my mobile phone these days (a Samsung Galaxy Ultra S23) but occasionnaly also use “regular” cameras. As opposed to my phone, which saves the files with a filename that includes date and time (YYYYMMDD_HHMMSS.jpg), these cameras typically just use some random name (e.g. P43435.jpg). This is impractical when combining photos from several cameras, so I prefer renaming the files with the same filename schema.
Fortunately, information about the capture date and time is usually stored in the EXIF information in the header of the image file. There are various tools for retrieving this, but I have found the easiest is to use a simple script in the terminal. This is my current version:
#!/bin/bash
# Please this script in the folder with JPG files.
# Loop through all JPEG files in the directory.
for file in *.jpg *.jpeg *.JPG *.JPEG; do
# Check if the file actually matches (in case there are no matches).
if [ -e "$file" ]; then
# Extract the DateTimeOriginal from EXIF data and format it as YYYYMMDD_HHMMSS.
datetime=$(exiftool -DateTimeOriginal -d "%Y%m%d_%H%M%S" "$file" | awk -F': ' '{print $2}')
# If the datetime is empty, skip this file.
if [ -z "$datetime" ]; then
echo "Skipping $file (no EXIF DateTimeOriginal found)"
continue
fi
# Initialize the new file name.
new_filename="${datetime}.jpg"
counter=1
# Check if the new file name already exists to avoid overwriting.
while [ -e "$new_filename" ]; do
new_filename="${datetime}_$counter.jpg"
((counter++))
done
# Rename the file.
echo "Renaming $file to $new_filename"
mv "$file" "$new_filename"
fi
done
If you want to try this yourself, save the script in a file with a name like rename_photos.sh and make it executable:
chmod +x rename_photos.sh
Then you can run the script like this:
./rename_photos.sh
and watch the magic unfold.