What\'s an easy way to convert 00:20:40.28
(HH:MM:SS) to seconds with a Bash script?
Split seconds can be cut out, it’s not essential.
I have this old shell function (/bin/sh compatible in the sense of POSIX shell, not bash) which does this conversion in integer math (no fractions in the seconds):
tim2sec() {
mult=1
arg="$1"
res=0
while [ ${#arg} -gt 0 ]; do
prev="${arg%:*}"
if [ "$prev" = "$arg" ]; then
curr="${arg#0}" # avoid interpreting as octal
prev=""
else
curr="${arg##*:}"
curr="${curr#0}" # avoid interpreting as octal
fi
curr="${curr%%.*}" # remove any fractional parts
res=$((res+curr*mult))
mult=$((mult*60))
arg="$prev"
done
echo "$res"
}
Outputs:
$ tim2sec 1:23:45.243
5025
It works with SS, MM:SS and HH:MM:SS only :)