Bash: How to copy timestamps using touch and regex

bashregextimestamp

Since this is more of a Bash question I think this is better suited for serverfault than superuser, even though I'm talking about media files.

I had to make a batch conversion of several media files, and all the output files have a new timestamp.

/somedir/
    file1.mpg     (correct timestamp)
    file1.mpg.m4v (wrong timestamp)
    file2.mpg     (correct timestamp)
    file2.mpg.m4v (wrong timestamp)
    ...

What I want to do is a batch copy of the timestamps so that each *.mpg.m4v gets the timestamp of the corresponding *.mpg file.

From my searching, it looks like I need to use touch -r and some regex with substitution to handle this.

Am I on the right track, and does anyone have any suggestions for how I need to do the regex (my regex knowledge, is bad, bad, bad) to handle this?

Best Answer

Let's see, how about...

for f in *.mpg; do
   touch -r "$f" "${f}.m4v"
done

No need for regexps, just to take the problem from the right side. It's much easier to circle through *.mpg and add .m4v to them than the contrary, although you could also write it the other way without regexps (just for fun):

for f in *.m4v; do
   touch -r "${f%\.m4v}" "$f"
done

If you want it done with one command, you could do that with find (restricting it to one level for safety):

find . -maxdepth 1 -name '*.mpg' -exec touch -r {} {}.m4v \;