I got a string as follow :
foo=0j0h0min0s
What would be the best way to convert it in seconds without using date ?
I tried something like this that sounded pretty nice but no luck :
#> IFS=: read -r j h min s <<<"$foo" #> time_s=$((((j * 24 + h) * 60 + min) * 60 + s)) ksh: syntax error: `<' unexpected
Any idea is welcome, I just can’t use date -d
to make conversion as it is not present on the system I am working on.
Advertisement
Answer
<<<"$foo"
is mainly a bash-ism. It is supported in some/newer ksh. (google ‘ksh here string’ ).
Your read is trying to split at :
, wich is not present in your input
If you first get rid of characters, you can split at blank (as ususal) and changing the here-string to a here-doc
#!/bin/ksh foo=1j2h3min4s read -r j h min s << END "${foo//[a-z]/ }" END # or echo "${foo//[a-z]/ }" | read -r j h min s time_s=$((((j * 24 + h) * 60 + min) * 60 + s)) echo ">$foo< = >${foo//[a-z]/ }< = $j|$h|$min|$s => >$time_s<" >1j2h3min4s< = >1 2 3 4 < = "1|2|3|4 " => >93784< # or using array, easy to assign, more typing where used typeset -a t=( ${foo//[a-z]/ } ) time_s=$(( (( t[0] * 24 + t[1]) * 60 + t[2]) * 60 + t[3] )) echo ">$foo< = >${foo//[a-z]/ }< = ${t[0]}|${t[1]}|${t[2]}|${t[3]} => >$time_s<"