rakeshr
rakeshr

Reputation: 1037

difference between times in a 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 compute the difference in time between two successive lines. Is there a way to do it in shell scripts / awk ?

Upvotes: 3

Views: 3807

Answers (2)

anubhava
anubhava

Reputation: 786136

Here is the awk 1 liner to get the time difference between 2 lines for input as above:

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

OUTPUT (for the input file as above)

Diff: 1293866425
Diff: 35
Diff: 114
Diff: 34
Diff: 362

Upvotes: 2

MJB
MJB

Reputation: 7686

A simplistic way would be to convert each line to seconds, then subtract the previous line from the current line. Easy in awk. If that is actually what you want, then here is a 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 silly, but that is easily remedied by defaulting to the same value. It also does not convert back to differences in hours, minutes, seconds, but I don't know if you need that.

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 weird but not as bad.

Upvotes: 5

Related Questions