Search code examples
bashexif

Bash script: creating a variable based on part of a file name / part of a string using EXIF data from photo


I have a massive amount of photos I want to store in a folder structure that organises them by the genuine month and year they were taken.

Each photo has EXIF data that I have used to rename each file based on the date created:

identify -verbose $file | grep Original

Which might return something like this (white space included):

    exif-DateTimeOriginal- 2004-03-24 15-54-48

Next I want to create folders for the month and year in this string but cannot figure out how to do this.

So far my script looks like this:

#!/bin/bash

IFS='
'

cd ~/Pictures/all-pics

for file in *;
do
[ -e $file ] || continue
mv $file "$file.jpeg"
echo $file

file="identify -verbose $file | grep Original"

# the lines I need to create these variables go here 

mv $file /Documents/all-pics/$year/$month/

done

I'm sure there are a few ways to do this without even renaming the file but as I am new to shell scripting I haven't found any good documentation on how to set variables based on EXIF properties such as these.

I started off by trying to create these variables using methods such as the below but I am clutching at straws:

year="    exif-DateTimeOriginal- $year-??-?? ??-??-??"
month="    exif-DateTimeOriginal- ??-$month-?? ??-??-??"

Solution

  • exiftool have extensible query options. It's based on Perl language.

    Example:

    exiftool -s3 "-DateTimeOriginal" -d "%Y %m" file.png
    -------8<------------------
    2023 01
    

    Within a script:

    #!/bin/bash
    
    for file; do
        read year month < <(exiftool -s3 "-DateTimeOriginal" -d "%Y %m" "$file")
        dir=$year/$month
        mkdir -p "$dir"
        echo mv "$file" "$dir"
    done
    

    Remove the echo command when the output looks satisfactory.

    Usage

    ./script <file(s)>