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

后端 未结 14 1938
难免孤独
难免孤独 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:09

    Try to use my solution with sed+awk:

    ps --pid $YOUR_PID -o etime= | sed 's/:\|-/ /g;' |\ 
    awk '{print $4" "$3" "$2" "$1}' |\
    awk '{print $1+$2*60+$3*3600+$4*86400}'
    

    it splits the string with sed, then inverts the numbers backwards ("DD hh mm ss" -> "ss mm hh DD") and calculates them with awk.

    $ echo 21-18:26:30 | sed 's/:\|-/ /g;' | awk '{print $4" "$3" "$2" "$1}' | awk '{print $1+$2*60+$3*3600+$4*86400}'
    1880790
    $ echo 15:28:37 | sed 's/:\|-/ /g;' | awk '{print $4" "$3" "$2" "$1}' | awk '{print $1+$2*60+$3*3600+$4*86400}'
    55717
    $ echo 48:14 | sed 's/:\|-/ /g;' | awk '{print $4" "$3" "$2" "$1}' | awk '{print $1+$2*60+$3*3600+$4*86400}'
    2894
    $ echo 00:01 | sed 's/:\|-/ /g;' | awk '{print $4" "$3" "$2" "$1}' | awk '{print $1+$2*60+$3*3600+$4*86400}'
    1
    

    Also you can play with sed and remove all non-numeric characters from input string:

    sed 's/[^0-9]/ /g;' | awk '{print $4" "$3" "$2" "$1}' | awk '{print $1+$2*60+$3*3600+$4*86400}'
    

提交回复
热议问题