How to rename a folder of images or movies by the date and time they were taken

If you’re renaming one file, this is overkill, but if you’re renaming several hundred files, this will make your life so much better. This might be useful if your smartphone happens to name your pictures and videos using the least useful convention possible: integers that increment from 1, starting when you got your phone. (Please do not leave a comment telling me to switch to Android, thanks.)

The following instructions should work on Ubuntu 20.04, and it assumes you have a basic knowledge of the command line.

JPEG images

First, if you don’t already have it, install jhead like so:

$ sudo apt install jhead

Then cd to your folder of images and run the following command:

$ jhead -autorot -nf%Y-%m-%d\ %H-%M-%S *.jpg

This will rename all the .jpg files in that folder by the date/time they were taken.

You might need to repeat it for .JPG, .JPEG, etc.

Warning: If it can’t find metadata for the date/time inside that file, it will rename the file using the file’s creation date, which may or may not be what you want.

Movies

This one’s more complicated. You have to write a short shell script.

Step one: Learn Emacs.

Lol just kidding, use whatever text editor you want.

Make a new file called rename-movies-by-date.sh and put the following in it:

#!/bin/bash

filetype=$1
folder=$2

folderfiles="$folder/*.$filetype"

for file in $(ls $folderfiles); do
    datetime=$(mediainfo $file | grep Tagged\ date | head -n 1 | grep -o [0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\ [0-9]\\{2\\}:[0-9]\\{2\\}:[0-9]\\{2\\} | sed 's/:/-/g')
    if [ "$datetime" != "" ]
    then
	newname="$folder/$datetime.$filetype"
	mv "$file" "$newname"
	
    else
	echo "No metadata for $file"
    fi
done

Then make the file executable:

$ chmod +x rename-movies-by-date.sh

Now you can run your script!

$ ./rename-movies-by-date.sh MOV '/home/yourname/Videos'

You might have to run this several times for each type of file extension .mov, .MOV, .mp4, etc.

You can even open a terminal window and drag the shell script on it, then type MOV and then drop the folder on it, and it should work!

Warning: Make sure that there’s no trailing slash at the end of the folder. Also, the script doesn’t handle file names with spaces in them nicely, so get rid of them first. (In Nautilus, select all the files, then press F2 and do a find/replace for spaces to underscores, maybe?)

Published by

The Grey Literature

This is the personal blog of Benjamin Gregory Carlisle PhD. Queer; Academic; Queer academic. "I'm the research fairy, here to make your academic problems disappear!"

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.