Reputation: 85
Below is the sample file. (test.txt)
First 2015-05-21 11:03:19.000708 Second 2015-05-20 16:17:05.101111 Third 2015-05-21 11:03:30.000204 Forth 2015-05-21 11:03:23.000611 Fifth 2015-05-21 11:03:27.000519 Sixth 2015-05-21 11:03:23.000470
If current time is "Thu May 21 12:03:09 EDT 2015", I would like to see the expected output to be something like following:
First 01:00:10 Second 23:43:39 Third 00:57:30 Forth 00:57:37 Fifth 00:57:33 Sixth 00:57:37
I am trying with below command. Can you please try to fix it..
cat test.txt |awk '{cmd="date -d \""$2" "$3"\"" curr=`date` cmd | getline var1 curr | getline var2 lag=var2-var1 print $1, lag close(cmd)}'
Thanks in advance.
Upvotes: 0
Views: 157
Reputation: 44043
With GNU awk, using its built-in time functions:
gawk 'BEGIN { now = systime() } { t = $2 " " $3; gsub(/[-:]/, " ", t); t = mktime(t); dt = now - t; s = dt % 60; m = int(dt / 60 % 60); h = int(dt / 3600); print $1, h ":" m ":" s }' filename
This works as follows:
BEGIN { # in the beginning:
now = systime() # remember the current time (as seconds since Epoch)
}
{
t = $2 " " $3 # construct time stamp from input line, in
gsub(/[-:]/, " ", t) # a format that mktime understands
t = mktime(t) # convert to seconds since Epoch
dt = now - t # diff to now
s = dt % 60 # isolate seconds,
m = int(dt / 60 % 60) # minutes,
h = int(dt / 3600) # hours
print $1, h ":" m ":" s # then print the lot.
}
One might consider using strftime
to format the output, but that'll break because of DST and because days are only 24 hours long. It's better to do it manually.
Upvotes: 4