Parse ps' “etime” output and convert it into seconds

后端 未结 14 1934
难免孤独
难免孤独 2020-12-30 12:43

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 se

14条回答
  •  时光说笑
    2020-12-30 13:13

    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
    

提交回复
热议问题