These are possible output formats for ps h -eo etime
21-18:26:30
15:28:37
48:14
00:01
How to parse them into seconds?
- Please assume at least 3 digits for the days part as I don't know how long it can be.
- The output will be
egreped
to one only line so no need for a loop.
With awk:
Run with :
Output:
And finally, if you want to pipe to the parser, you can do something like this:
Here's mine Perl one liner:
Undefined values are rendering to zero, so they won't have effect on the sum of seconds.
Ruby version:
Another bash option as a function; uses tac and bc for math.
Yet another bash solution, which works any number of fields:
ps -p $pid -oetime= | tr '-' ':' | awk -F: '{ total=0; m=1; } { for (i=0; i < NF; i++) {total += $(NF-i)*m; m *= i >= 2 ? 24 : 60 }} {print total}'
Explanation:
-
to:
so that string becomes1:2:3:4
instead of '1-2:3:4', set total to 0 and multiplier to 1Try to use my solution with sed+awk:
it splits the string with sed, then inverts the numbers backwards ("DD hh mm ss" -> "ss mm hh DD") and calculates them with awk.
Also you can play with sed and remove all non-numeric characters from input string: