views:

140

answers:

4

Whats an easy way to convert 00:20:40.28 to seconds with a bash script? (Split seconds can be cut out, it’s not essential.)

+1  A: 

I haven't tested this but, I think this is how you'd split the string. Followed by multiplying by the appropriate amounts for hours and minutes.

mytime=’00:20:40.28′
part1=${mytime%%:*}; rest=${mytime#*:}
part2=${rest%%:*}; rest=${rest#*:}
part3=${rest%%:*};
netricate
+1  A: 

with the shell,

#!/bin/bash

d="00:20:40.28"
IFS=":"
set -- $d
hr=$(($1*3600))
min=$(($2*60))
sec=${3%.*}
echo "total secs: $((hr+min+sec))"
ghostdog74
+2  A: 

Try this:

T='00:20:40.28'
SavedIFS="$IFS"
IFS=":."
Time=($T)
Seconds=$((${Time[0]}*3600 + ${Time[1]}*60 + ${Time[2]})).${Time[3]}
IFS="$SavedIFS"

echo $Seconds

($<string>) splits <string> based on the splitter (IFS).

${<array>[<index>]} returns the element of the <array> at the <index>.

$((<arithmetic expression>)) performs the arithmetic expression.

Hope this helps.

NawaMan
This fails when ${Time[2]} contains a decimal point.
dreamlax
`IFS=":."` and `Seconds=$(( ... ))${Time[3]}`
Dennis Williamson
Thanks both of you, I miss that.
NawaMan
+3  A: 

Try awk. As a bonus, you can keep the split seconds.

echo "00:20:40.25" | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }'
dreamlax
Thanks, this is a very clean way of doing it, just what I wanted.As well maths isn’t really my strong point.
Mint