Bash – Changing a file’s modified date based on date in file name

bashfilesshell-scripttimestamps

I have a directory full of photos with file names in this format:
IMG-20160305-WA0001.jpg. The date taken is obviously in the file title.
Unfortunately the date modified on all files is today. I want to set them back to the correct date.

I am thinking of a bash script that would extract the date portion in the name and then for example touch -a -m -t 201603050900 IMG-20160305-WA0000.jpg for each file in turn (using correct date for each one). The time of day does not matter.

Best Answer

Example using bash string manipulation only to extract the date:

#!/bin/bash

for name in IMG-[0-9]*.jpg; do
    touch -amt ${name:4:8}0900 "$name"
done
Related Question