Extract date from filename and set timestamp

I have lots of files in this format:
dvgrab-2003.06.29_15-30-24.mpg

The numbers represents the date and time (YYYY.MM.DD_HH-MM-SS)

How can I extract the dates from the filenames, and use the dates in the file timestamp?

I guess this can be done by using "find", "sed" and "touch"?

Can anyone help, please?

BR,
Q

using find to list and sed to switch the format to a timestamp touch can use we get the following work of art.

for i in $(find $document_root -name dvgrab-\*.mpg) ; do
   touch -t $(echo $i | sed s/dvgrab-\([0-9]\{4\}\)\.([0-9]\{2\}\)\.\([0-9]\{2\}\)_\([0-9]\{2\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\)/\1\2\3\4\5\6/')  $i
done

Thanks for your suggestion, but this didn't do much. Could there be a typo somewhere?

BR,
Q

echo 'dvgrab-2003.06.29_15-30-24.mpg' |\
while read line
do
date_=`echo ${line#*-}|sed 's/_/ /;s/.mpg$//;s/-/:/g;s/\./-/g'`
echo "date: $date_"
echo "timestamp: "`date -d "$date_" "+%s"`
done
date: 2003-06-29 15:30:24
timestamp: 1056925824

I've done an attempt to fix your "work of art" :slight_smile:

for i in $(find $document_root -name dvgrab-\*.mpg) ; do
    touch -t $(echo $i | sed 's/dvgrab-\([0-9]\{4\}\)\.\([0-9]\{2\}\)\.\([0-9]\{2\}\)_\([0-9]\{2\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\).mpg/\1\2\3\4\5.\6/')  $i;
done

My problem now is that touch tries to set the timestamp with the directories in front. How can I strip out the leading dirs?

touch: invalid date format `./dir2/200306291530.24'
touch: invalid date format `./dir1/200306291004.25'

Any help appreciated!

BR,
Q

Try with

basename "$i"
#instead of
echo $i

This did the trick:

for i in $(find $document_root -name dvgrab-\*.mpg) ; do
     touch -t $(echo $i | sed 's/.*dvgrab-\([0-9]\{4\}\)\.\([0-9]\{2\}\)\.\([0-9]\{2\}\)_\([0-9]\{2\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\).mpg/\1\2\3\4\5.\6/')  $i;
 done

Thanks a lot for your help!