Friday, December 11, 2009

Awk - sum two times of hh-mm-ss format


2nd and 3rd field for input file 'file.txt' is in hh:mm:ss format.

$ cat file.txt
#slno round1 round2
505 01:54:15 00:24:05
509 01:34:39 00:23:03
503 01:51:55 00:22:55
503 01:45:10 00:12:15

Required:

- Sum $2 and $3 of the above file and print it as the 4th field in 'seconds' format.


The awk solution:

$ awk '
function convert(t) {

split(t,Arr,":")
return Arr[1]*3600+Arr[2]*60+Arr[3]

}

/^#/ {print $0,"\ttotal(sec)"; next}
{print $0,"\t",convert($2)+convert($3) }
' file.txt

Output:

#slno round1 round2 total(sec)
505 01:54:15 00:24:05 8300
509 01:34:39 00:23:03 7062
503 01:51:55 00:22:55 8090
503 01:45:10 00:12:15 7045

Related posts:

- Convert seconds to hh:mm:ss format in Bash script
- Find time between two dates using Bash
- More of Linux/UNIX date command
- Expand entries in file using awk in Bash

4 comments:

Anonymous said...

Thanks - just what I needed! :-)

SEMBU said...

Good Site

SEMBU said...

Good site

Unknown said...


eval "`echo 'TAB=qtq' | tr 'qt' '\47\11'`"

sep=$TAB

f='file.txt' # the file is TAB separated

dc -e "
# load up the main stack
$(< $f sed -e '/^#/d;h;s/^\S\+\s\+//;y/:/ /;H;g;s/\(.*\)\n/[\1] /')

# reg 'c' holding a tab
[$TAB]sc

# reg 'a' converting hh:mm:ss => seconds
[r60*+r3600*+]sa

# push the lines and total seconds onto stack 'x'
[laxsslaxls+SxSxlk1+skz3!>b]sb

# pop stack 'x' to display lines and total seconds
[LxnlcnLxplk1-sklk1!>d]sd

# initialize reg 'k' & execute regs 'b' & 'd' to generate results
0sklbxldx
" |
sed -e '
1i\
.TS\
tab('"$sep"');\
c c c c\
l l l n.\
'"#slno${sep}round1${sep}round2${sep}total(sec)"'
s/^\s\*//;s/\s\*$//;s/\s\+/\t/g
$a\
.TE
' | tbl - | nroff -Tascii -ms | grep '.'

© Jadu Saikia www.UNIXCL.com