Skip to content
Advertisement

How to do parsing of Elapsed time in seconds in linux

I want to do parsing of Elapsed time in seconds .Time formats given below:

1) 3 day 18h
2) 3 day
3) 3h 15min
4) 3h 
5) 15min 10sec
6) 15min 
7) 10sec

i’m getting values from systemctl status cassandra | awk '/(Active: active)/{print $9, $10,$11}' Now storing it’s value in variable A,like

A=$(systemctl status cassandra | awk '/(Active: active)/{print $9, $10,$11}'

now A has input as 3 day 18h or 3 day etc. More examples-

A=3 day 18h or 3 day or 3h 15min or 3h or 15min 10sec or 15min or 10sec

now take different values of A, and parse in seconds.

Advertisement

Answer

What you want to achieve could be done directly in awk using the following line :

$ systemctl status cassandra | awk '/(Active: active)/{s=$6" "$7;gsub(/-|:/," ",s); print systime() - mktime(s)}'

This will give you the running time directly based on the start-time and not on the approximated running time printed by systemctl.

If this approach is not working then I suggest to use the date command to do all the parsing. If you can change the h by hour in your examples, then you can do the following :

$ date -d "1970-01-01 + 3day 18hour 15min 16sec" +%s
324916

If you cannot, then I suggest the following. If duration is stored in the variable $duration, then you do

$ date -d "1970-01-01 + ${duration/h/hour}" +%s

Having spaces between the numbers and the strings day, h,min or sec does not matter.

The idea of this is that you ask date to compute everything for you as %s returns the unix time since 1970-01-01 in seconds.

man date: %s seconds since 1970-01-01 00:00:00 UTC

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement