Skip to content

Instantly share code, notes, and snippets.

@Nateowami
Last active December 28, 2016 08:46
Show Gist options
  • Save Nateowami/26768957f4c36e01e585a3da87afad28 to your computer and use it in GitHub Desktop.
Save Nateowami/26768957f4c36e01e585a3da87afad28 to your computer and use it in GitHub Desktop.
Rename According to Image or Video Metadata

Bash one-liners to rename images or videos according to metadata (date or dimensions)

Pictures

jhead -nIMG_%Y%m%d_%H%M%S *.jpg

Short and simple, jhead takes a format string after the -n CLI flag. It only works with JPEGs though. On Ubuntu 16.04, install the jhead package.

Videos

for i in *.3gp; do mv -i "$i" "$(exiftool -CreateDate "$i" | awk -F ': ' '{print $2}' | sed -e 's/:/-/g' -e 's/ /_/g').3gp"; done

Breakign it down, here's what's run in the loop:

mv -i "$i" "$(exiftool -CreateDate "$i" | awk -F ': ' '{print $2}' | sed -e 's/:/-/g' -e 's/ /_/g').3gp"

exiftool can be installed on Ubuntu 16.04 by installing the libimage-exiftool-perl package. Don't know about other versions or distors.
exiftool -CreateDate "$i" prints the date the video was filmed. This is piped to awk and sed for manipulation, which I didn't write myself. This one-liner is heavily based on this Ask Ubuntu answer: http://askubuntu.com/a/346025/289003

Moving pictures to directories named by the dimensions

In other words, a 100x100 image will be put in a directory named 100x100.

for file in *.jpg; do mkdir `identify -format '%wx%h' $file`; cp -i $file `identify -format '%wx%h' $file`/$file; done

Breaking it down to the body of the loop:

do mkdir `identify -format '%wx%h' $file`; cp -i $file `identify -format '%wx%h' $file`/$file

You'll notice identify -format '%wx%h' $file is in there twice. That's because cp doesn't create the directory it's copying to if it doesn't exist. So first mkdir makes the directory. This fails as soon as a second image with the same dimensions is found: mkdir: cannot create directory ‘100x100’: File exists. We could check if the directory existed first, but this was a one-off. Also, instead of running identify -format '%wx%h' $file twice, it would be better to store it in a variable. But again, it's a one-off and I'm bad at shell scripting.
For the identify command you'll need ImageMagick.
This one-liner is heavily based on this SO answer: http://stackoverflow.com/a/4884707/3714913

Final Note

I wrote this mostly for a personal reference. As is, it's not very flexible or informative. Feel free to ask questions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment