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.

  • 1
    And your question is... what ? Please do not make us guess here. – MelBurslan Apr 22 '16 at 20:40
  • Keep on thinking. ;) Alternatively, you can edit your post so that it actually contains a question. Fair? – Wildcard Apr 22 '16 at 20:46
  • 2
    Possible duplicate of Change last edited date – John Militer Apr 22 '16 at 20:48
  • 1
    @John That's not a duplicate. That question explains how to set a file's date, not how to do it automatically based on the file name. – Gilles Apr 22 '16 at 22:34

Example using bash string manipulation only to extract the date:


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

From your example, assuming that all of the files have a valid yyyymmdd date, you can extract the date from the filename and apply that in the command cited:

for name in IMG-*-W*.jpg
    date="$(echo "$name" | sed -e 's/^IMG-//' -e 's/-W.*//')"
    touch -a -m -t ${date}0900 "$name"

If some file hasn't a valid date, that is more work. But you can test that in bash with a regular expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.