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

3 comments:

Chris said...

Thanks - just what I needed! :-)

SEMBU said...

Good Site

SEMBU said...

Good site

© Jadu Saikia www.UNIXCL.com