[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? ...



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/
  '
  )
))

On Fri, Jul 18, 2025 at 7:09 PM Greg Wooledge <greg@wooledge.org> wrote:
>
> On Fri, Jul 18, 2025 at 18:59:06 -0700, Michael Paoli wrote:
> > echo $(( $(echo 07:08:09 | sed -e 's/^0*\([0-9]\)/3600 * \1 +
> > /;s/:0*\([0-9]:\)/60 * \1/;s/:0*\([0-9]\)$/ + \1/;') ))
>
> This one is missing some * operators.  You're only capturing a single
> digit in each segment, but there could be two digits (or maybe even
> more in the first segment).
>
> hobbit:~$ echo $(( $(echo 07:18:19 | sed -e 's/^0*\([0-9]\)/3600 * \1 + /;s/:0*\([0-9]:\)/60 * \1/;s/:0*\([0-9]\)$/ + \1/;') ))
> bash: 3600 * 7 + :18:19 : syntax error: operand expected (error token is ":18:19 ")
>
> Realistically, though, why are people so *bent* on writing "one-liners"?
> It's less efficient and less readable than the straightforward code.
>
> Longer code is not worse.  It's often better.
>


Reply to: