Search code examples
batch-fileawksedcygwingnu

Batch - How to perform mathematical operations on time codes?


I've been working on a batch script, to change some .xml files format/type.

It's almost done, but I'm facing a problem changing the time codes.

Here is an example

  <Events>
    <Event In="00:00:20.650" Out="00:00:22.970"
    <Event In="00:00:23.050" Out="00:00:26.300"

This Time Format hh:mm:ss.ms should be changed to hh:mm:ss:ff

which means, changing the Milliseconds to Frames.

The Formula for doing so goes like this: ms*25/1000 or for simplicity ms*0.025

Output should be

  <Events>
    <Event In="00:00:20:16" Out="00:00:22:24"
    <Event In="00:00:23:01" Out="00:00:26:08"

Notes

  • 0.025 is the number of frames per Milliseconds.
  • The number of frames MUST be an integer w/o any fractional component.
  • I'm Using GNUWin and Cygwin library Tools, so it's okay to use bc expr , tr , awk sed or whatever solution to get the job done.

Solution

  • You can do it with an awk script:

    script.awk

    { 
      re = "[0-9]{2}:[0-9]{2}:[0-9]{2}.([0-9]{3})"
      while( match( $0, re, grps) ) {
        frames = sprintf("%02.0f",( grps[1] *0.025 ) )
        gsub( "." grps[1], ":" frames)
      }
      print
    }
    

    Run it like this awk -f script.awk yourfile.

    It tries to match such a timestamp and captures the last part (the milliseconds) into grps[1]. Then the calculation is done and sprintf is used to format the frames.

    After that gsub replaces the milliseconds with the frames.