LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   adding time in hh:mm:ss format (https://www.linuxquestions.org/questions/linux-newbie-8/adding-time-in-hh-mm-ss-format-864705/)

thomsa 02-24-2011 03:23 AM

adding time in hh:mm:ss format
 
One of my scripts generated an output like this:
0:0:35
0:0:36
0:0:28
0:0:37
0:0:43
0:1:2

This is actually in a time format(hh:mm:ss) and how do i add all the values and get the sum in seconds .
the output should be in seconds like
total number of seconds : 241 secs

JimmyKrak 02-24-2011 04:31 AM

time="1:2:3"

let h=`echo $time|cut -d":" -f1
let m=`echo $time|cut -d":" -f2
let s=`echo $time|cut -d":" -f3

let seconds=$h*3600+$m*60+$s

druuna 02-24-2011 04:53 AM

Hi,

Code:

#!/bin/bash

awk -F: 'BEGIN { totSecs = 0 }
{ totSecs = totSecs + 3600 * $1 + 60 * $2 + $3 }
END { print "Total number of seconds: " totSecs }
' infile

infile holds the output of the script.

Example run:
Code:

$ cat infile
0:0:35
0:0:36
0:0:28
0:0:37
0:0:43
0:1:2

$ ./total.secs.sh
Total number of seconds: 241

@JimmyKrak: The first three let statements are missing a closing `

Hope this helps.

colucix 02-24-2011 04:55 AM

In alternative to what suggested by JimmyKrak, you can spare the cut commands to do the conversion:
Code:

echo $time | awk -F: '{print $1*3600 + $2*60 + $3}'
If you want to retrieve the sum after the script has terminated:
Code:

yourscript.sh | awk -F: '{sum += $1*3600 + $2*60 + $3} END{print sum}'
Edit: beaten by druuna! ;)

JimmyKrak 02-24-2011 05:50 AM

druuna, You're right. That's what I get for not testing better. Thanks.

thomsa 02-24-2011 07:20 AM

Quote:

Originally Posted by druuna (Post 4269450)
Hi,

Code:

#!/bin/bash

awk -F: 'BEGIN { totSecs = 0 }
{ totSecs = totSecs + 3600 * $1 + 60 * $2 + $3 }
END { print "Total number of seconds: " totSecs }
' infile

infile holds the output of the script.

Example run:
Code:

$ cat infile
0:0:35
0:0:36
0:0:28
0:0:37
0:0:43
0:1:2

$ ./total.secs.sh
Total number of seconds: 241

@JimmyKrak: The first three let statements are missing a closing `

Hope this helps.

thank you ...it works :)

druuna 02-24-2011 07:27 AM

You're welcome :)


All times are GMT -5. The time now is 05:28 AM.