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

后端 未结 14 2061
难免孤独
难免孤独 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 13:23

    Another bash option as a function; uses tac and bc for math.

    function etime2sec () {
       # 21-18:26:30
       #    15:28:37
       #       48:14
       #       00:01
    etimein=$1
    hassec=no ; hasmin=no ; hashr=no ; hasday=no
    newline=`echo "${etimein}" | tr ':' '-' | tr '-' ' ' | tac -s " " | tr '\n' ' '`
    for thispiece in $(echo "${etimein}" | tr ':' '-' | tr '-' ' ' | tac -s " " | tr '\n' ' ') ; do
      if [[ $hassec = no ]] ; then
        totsec=$thispiece
        hassec=yes
      elif [[ $hasmin = no ]] ; then
        totsec=`echo "$totsec + ($thispiece * 60)" | bc`
        hasmin=yes
      elif [[ $hashr = no ]] ; then
        totsec=`echo "$totsec + ($thispiece * 3600)" | bc`
        hashr=yes
      elif [[ $hasday = no ]] ; then
        totsec=`echo "$totsec + ($thispiece * 86400)" | bc`
        hashr=yes
      fi
    done
    echo $totsec
    }
    

提交回复
热议问题