Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse ps' "etime" output and convert it into seconds

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.
like image 297
Clodoaldo Neto Avatar asked Feb 01 '13 18:02

Clodoaldo Neto


1 Answers

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:

  1. replace - to : so that string becomes 1:2:3:4 instead of '1-2:3:4', set total to 0 and multiplier to 1
  2. split by :, start with the last field (seconds), multiply it by m = 1, add to total second number, m becomes 60 (seconds in a minute)
  3. add minutes fields multiplied by 60, m becomes 3600
  4. add hours * 3600
  5. add days * 3600 * 24
like image 65
Fluffy Avatar answered Oct 02 '22 06:10

Fluffy