[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Is there a POSIX compliant way of turning a "HH:MM:SS" formatted string to seconds? ...



On Sat, Jul 19, 2025 at 10:14:49 +0700, Max Nikulin wrote:
> A mathematical trick may be used instead even if external processes like sed
> are considered as undesired overhead
> 
> for i in 0 09 008 59 080; do i1=1$i; i2=2$i; echo "$i = $((2*i1 - i2))";
> done
> 
> 0 = 0
> 09 = 9
> 008 = 8
> 59 = 59
> 080 = 80

Oh, I like this one.  I'm gonna add that to my wiki.


On Fri, Jul 18, 2025 at 21:08:09 -0700, Michael Paoli wrote:
> echo \
> $((
>   $(
>     d12='\([0-9]\{1,2\}\)'
>     echo 09:10:11 |
>   sed -e '
>     s/^/ /
>     s/:/ /g
>     s/ 0*\([0-9]\)/ \1/g
>   '"  s/^ $d12 $d12 $d12"'$/3600 * \1 + 60 * \2 + \3/
>   '
>   )
> ))

I don't like this one as much.  It's better than the original one-liner
(both because it's actually correct -- I think! -- and because it's in
a format that's a little bit easier to read), but it still looks like
it was written by someone who is bound and determined to use sed for this,
no matter how difficult it may be.

Also, the use of [0-9]\{1,2\} for the first segment means you're
hard-capping this to 99:59:59 and will never be able to handle 100:23:45.
That might be OK, or not.  I don't know whether there are any restrictions
on the durations the OP is dealing with.  I would've used \{1,\} to
remove the two-digit limit, if I had to do it this way.


Reply to: