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

后端 未结 14 2089
难免孤独
难免孤独 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 12:57

    #!/bin/bash
    echo $1 | sed 's/-/:/g' |  awk -F $':' -f <(cat - <<-'EOF'
      {
        if (NF == 1) {
            print $1
        }
        if (NF == 2) {
            print $1*60 + $2
        }
        if (NF == 3) {
            print $1*60*60 + $2*60 + $3;
        }
        if (NF == 4) {
            print $1*24*60*60 + $2*60*60 + $3*60 + $4;
        }
        if (NF > 4 ) {
            print "Cannot convert datatime to seconds"
            exit 2
        }
      }
    EOF
    ) < /dev/stdin
    

    Then to run use:

    ps -eo etime | ./script.sh 
    

提交回复
热议问题