I've got a number of files of which I want to change the modification date in linux. The modification date is saved in the filename.
So I've got files, whose name is for example "IMG_20180101_010101.jpg", but the modification date is today. I want to change the modification date to 2018-01-01 01:01:01, as in the filename. I've tried with find and touch:
find . -iname 'IMG*' -print | while read filename; do touch -t {filename:7:8} "$filename"; done
When I do this I always get an error ("invalid date format: {filename:7:8}).
What am I doing wrong?
If you want to set the file timestamp according to the filename, you can try this:
find -type f -name "IMG_*" -exec bash -c 'touch -t $(sed "s/.*IMG_\([0-9]\{8\}\)_\([0-9]\{4\}\)\([0-9]\{2\}\).jpg$/\1\2.\3/" <<< "$1") "$1"' _ {} \;
As mentionned in the touch
man page, the option -t
expects a format [[CC]YY]MMDDhhmm[.ss]
. That's the purpose of the sed
command.