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-?? ??-??-??"
CodePudding user response:
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)>
CodePudding user response:
One option might be to use bash regex to capture the yyyy-mm
portion of the original date EXIF data and then use bash parameter expansion to extract the year and the month:
original_date=" exif-DateTimeOriginal- 2004-03-24 15-54-48"
printf "original date is $original_date\n"
if [[ "$original_date" =~ ([[:digit:]]{4}-[[:digit:]]{2}) ]] ; then
year_month="${BASH_REMATCH[0]}"
year="${year_month%%-*}"
month="${year_month##*-}"
printf "year is %s\nmonth is %s\n" "$year" "$month"
fi
Output:
original date is exif-DateTimeOriginal- 2004-03-24 15-54-48
year is 2004
month is 03
The $year
and $month
variables can be used to build your path for creating the directories and moving the files.