The difference between the time in the file

I have a file in this format

02:20:25
02:21:00
02:22:54
02:23:28 
02:29:30 
....

I need to calculate the time difference between two consecutive lines. Is there any way to do this in shell scripts / awk?

+3
source share
2 answers

The simplest way would be to convert each line into seconds and then subtract the previous line from the current line. Easy in awk. If this is actually what you want, then there is the possibility:

awk -f: '{\
  seconds = $1*60*60 + $2*60 + $3; \
  print seconds-prev_seconds; \
  prev_seconds=seconds;\
}' file.dat

This leaves the first difference as stupid, but it is easily fixed by default to the same value. It also does not convert back to the difference in hours, minutes, seconds, but I do not know if you need it.

But to fix the first line, just say

awk -f: '{\
  seconds = $1*60*60 + $2*60 + $3; \
  if (prev_seconds == 0) prev_seconds = seconds; \
  print seconds-prev_seconds; \
  prev_seconds=seconds;\
}' file.dat

Now the first difference is 0, which is still strange, but not so bad.

+4

awk 1, , :

awk 'BEGIN{prevDt=0;} {gsub(/:/, " ", $1); dt=mktime("2011 01 01 " $1); print "Diff: " (dt-prevDt); prevDt=dt;}' 

OUTPUT ( , )

Diff: 1293866425
Diff: 35
Diff: 114
Diff: 34
Diff: 362
+2

All Articles