Skip to content
Advertisement

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.

Advertisement

Answer

With awk:

#!/usr/bin/awk -f  
BEGIN { FS = ":" }
{
  if (NF == 2) {
    print $1*60 + $2
  } else if (NF == 3) {
    split($1, a, "-");
    if (a[2] != "" ) {
      print ((a[1]*24+a[2])*60 + $2) * 60 + $3;
    } else {
      print ($1*60 + $2) * 60 + $3;
    }
  }
}

Run with :

awk -f script.awk datafile

Output:

1880790
55717
2894
1

And finally, if you want to pipe to the parser, you can do something like this:

ps h -eo etime | ./script.awk
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement