Reputation: 249
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?
Upvotes: 0
Views: 435
Reputation: 46
If I understood good, you would like to write the file names in your own format. What about this script:
#!/bin/bash
suffix=".jpg"
for file in "IMG*"; do # Careful, the loop will break on whitespace
fileDate=$(echo $file| cut -d'_' -f 2)
year=${fileDate:0:4}
month=${fileDate:4:2}
day=${fileDate:6:2}
fileHour=$(echo $file| cut -d'_' -f 3 | sed -e s/$suffix//)
hour=${fileHour:0:2}
min=${fileHour:2:2}
secs=${fileHour:4:2}
newName="$year-$month-$day $hour:$min:$secs$suffix"
mv $file "$newName"
done
Upvotes: 0
Reputation: 13249
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.
Upvotes: 1