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

后端 未结 14 1935
难免孤独
难免孤独 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 
    
    0 讨论(0)
  • 2020-12-30 12:57

    Works on AIX 7.1:

    ps -eo etime,pid,comm | awk '{if (NR==1) {print "-1 ",$0} else {str=$1; sub(/-/, ":", str="0:0:"str); n=split(str,f,":"); print 86400*f[n-3]+3600*f[n-2]+60*f[n-1]+f[n]," ",$0}}' | sort -k1n
    
    0 讨论(0)
  • 2020-12-30 12:59

    Think I might be missing the point here but the simplest way of doing this is:

    ps h -eo etimes
    

    Note the 's' on the end of etime.

    0 讨论(0)
  • 2020-12-30 12:59
    [[ $(ps -o etime= REPLACE_ME_WITH_PID) =~ ((.*)-)?((.*):)?(.*):(.*) ]]
    printf "%d\n" $((10#${BASH_REMATCH[2]} * 60 * 60 * 24 + 10#${BASH_REMATCH[4]} * 60 * 60 + 10#${BASH_REMATCH[5]} * 60 + 10#${BASH_REMATCH[6]}))
    

    Pure BASH. Requires BASH 2+ (?) for the BASH_REMATCH variable. The regex matches any of the inputs and places the matched strings into the array BASH_REMATCH, which parts of are used to compute number of seconds.

    0 讨论(0)
  • 2020-12-30 13:03

    Ruby version:

    def psETime2Seconds(etime)
      running_secs = 0
      if etime.match(/^(([\d]+)-)?(([\d]+):)?([\d]+):([\d]+)$/)
        running_secs += $2.to_i * 86400 # days
        running_secs += $4.to_i * 3600  # hours
        running_secs += $5.to_i * 60    # minutes
        running_secs += $6.to_i         # seconds
      end
      return running_secs
    end
    
    0 讨论(0)
  • 2020-12-30 13:04

    A version for Python:

    ex=[
        '21-18:26:30',
        '06-00:15:30',
        '15:28:37',
        '48:14',
        '00:01'
        ]
    
    def etime_to_secs(e):
        t=e.replace('-',':').split(':')
        t=[0]*(4-len(t))+[int(i) for i in t]
        return t[0]*86400+t[1]*3600+t[2]*60+t[3]
    
    for e in ex:
        print('{:11s}: {:d}'.format(e, etime_to_secs(e)))
    
    0 讨论(0)
提交回复
热议问题