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
#!/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
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
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.
[[ $(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.
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
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)))