3

I nee to subtract two lines which is in the format of time in shell. The time format is hh:mm:ss I used the code below to get the time.

cat /var/log/kern.log |grep usb |tail -2| awk '{print $3}'

The output of the above code is

18:23:24
18:20:20

How can I find the difference in seconds?

8

I would take a step further (inspired by this post):

# => 18:23:24 --> 66204
grep usb /var/log/kern.log|tail -2|awk '{print $3}'|awk -F: '{print ($1 * 3600) + ($2 * 60) + $3 }'

So, after I had:

66204
66020

You could then do:

echo $((66204-66020)) # => 184
| improve this answer | |
  • 2
    Why are you piping awk into awk ? – user78605 Nov 10 '14 at 23:34
  • I'm separating concerns: the first awk gives me the hh:mm:ss format. The second awk transforms the hhh:mm:ss into integers. For me, it cuts down on cognitive load. – David Weiser Nov 11 '14 at 16:59
  • @DarkHeart: what would you recommend? – David Weiser Nov 12 '14 at 18:16
4

A more general solution because it works with times from different dates, too:

echo "18:23:24
18:20:20" | 
  (read later_time; read former_time;
    former_seconds=$(date --date="$former_time" +%s);
    later_seconds=$(date --date="$later_time" +%s);
    echo $((later_seconds-former_seconds)) )
184
| improve this answer | |
0

If you use awk you can do it in one invocation

awk '
/usb/{
("date +%s -d "$3)|getline t[++i];
}
END{
print t[i-1]-t[i];
}' /var/log/kern.log
| improve this answer | |
0

Your entire pipeline in awk without lots of unnecessary pipes.
Similar to costas but without using any external commands.

awk '/usb/{split($3,a,":");b[++x]=(a[1]*3600)+(a[2]*60)+a[3]}END{print b[x-1]-b[x]}' /var/log/kern.log

Heres just the last bit with the dates worked out if you decide to keep the pipes

 awk '{split($1,a,":");b[x++]=(a[1]*3600)+(a[2]*60)+a[3]}END{print b[0]-b[1]}'
| improve this answer | |
  • @Costas, there are only ever going to be two at the end of that pipe so it works fine, also the $2 was a typo and has been fixed :) – user78605 Nov 11 '14 at 10:30
  • Sorry I miss idea to remail all pipes – Costas Nov 11 '14 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.