I've log file in form like below:

log.txt

Unavailable 06.08.2014 23:59:36 - 07.08.2014 00:00:36
Unavailable 15.08.2014 04:53:32 - 15.08.2014 04:53:32
Available   15.08.2014 04:54:32 - 15.08.2014 05:17:32
Unavailable 15.08.2014 05:18:32 - 15.08.2014 05:18:32
Unavailable 15.08.2014 08:22:00 - 15.08.2014 08:22:00
Available   15.08.2014 08:23:00 - 17.08.2014 01:44:27
Unavailable 17.08.2014 01:45:27 - 17.08.2014 01:52:33
Available   17.08.2014 01:53:33 - 02.09.2014 11:07:21

I need to count unavailability time in seconds. I'm not any sed/awk guru so my apporach to this problem is very simple:

cat log.txt | grep "Unav" | sed -r 's/\<Unavailable\>//g;s/:/ /g;s/\./ /g' | 
awk -F- '{d2=mktime($2);d1=mktime($1);print d2-d1;}' | awk '{s+=$1} END {print s}'

I was suprised seeing that when date came across day (trough midnight) calculation goes wrong. Result from calculation of first line shows that difference was 31449660 seconds in EPOCH, so it will be Thu Dec 31 01:01:00 CET 1970. But result of calculation should be 60 seconds. Can someone explain me why this result was returned from system?

share|improve this question
up vote 3 down vote accepted

You don't need all that sed and grep if you are going to use awk. Also, the difference should be 60 seconds as it shows from the sample data.

From the man page:

mktime(datespec) Turn datespec into a timestamp in the same form as is returned by systime(). It is similar to the function of the same name in ISO C. The argument, datespec, is a string of the form "YYYY MM DD HH MM SS [DST]".

Try the following command:

awk '
$1 == "Unavailable" { 
    split ($2, d1, /[.]/);
    split ($3, t1, /:/);
    split ($5, d2, /[.]/);
    split ($6, t2, /:/);
    end   = mktime (d2[3]" "d2[2]" "d2[1]" "t2[1]" "t2[2]" "t2[3])
    start = mktime (d1[3]" "d1[2]" "d1[1]" "t1[1]" "t1[2]" "t1[3])
    print end - start
}' log.txt
60
0
0
0
426

This will print the difference in seconds. If you wish to print the output in another format you can use the strftime function from GNU awk library.

share|improve this answer
1  
As I say I'm not awk guru, but I see that You are thanks a lot. – michalp Sep 4 '14 at 6:56
1  
As I couldn't upvote your comment in "the answer posted from you know where", I do it here :D – fedorqui Sep 4 '14 at 13:13

On my system, man awk says mktime(datespec) requires the format YYYY MM DD HH MM SS. But you are passing 06 08 2014 23 59 36, which has the year and day swapped. You'll need to rearrange the fields.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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