Parse ps' "etime" output and convert it into seconds
Answer #1 100 %With awk:
#!/usr/bin/awk -f
BEGIN { FS = ":" }
{
if (NF == 2) {
print $1*60 + $2
} else if (NF == 3) {
split($1, a, "-");
if (a[2] != "" ) {
print ((a[1]*24+a[2])*60 + $2) * 60 + $3;
} else {
print ($1*60 + $2) * 60 + $3;
}
}
}
Run with :
awk -f script.awk datafile
Output:
1880790
55717
2894
1
And finally, if you want to pipe to the parser, you can do something like this:
ps h -eo etime | ./script.awk
Answer #2 100 %Yet another bash solution, which works any number of fields:
ps -p $pid -oetime= | tr '-' ':' | awk -F: '{ total=0; m=1; } { for (i=0; i < NF; i++) {total += $(NF-i)*m; m *= i >= 2 ? 24 : 60 }} {print total}'
Explanation:
- replace
-
to:
so that string becomes1:2:3:4
instead of '1-2:3:4', set total to 0 and multiplier to 1 - split by :, start with the last field (seconds), multiply it by m = 1, add to total second number, m becomes 60 (seconds in a minute)
- add minutes fields multiplied by 60, m becomes 3600
- add hours * 3600
- add days * 3600 * 24
Here's mine Perl one liner:
ps -eo pid,comm,etime | perl -ane '@t=reverse split(/[:-]/,$F[2]); $s=$t[0]+$t[1]*60+$t[2]*3600+$t[3]*86400; print "$F[0]\t$F[1]\t$F[2]\t$s\n"'
Undefined values are rendering to zero, so they won't have effect on the sum of seconds.
Answer #4 100 %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.
Answer #5 100 %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.
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}'