我有一根绳子,如下所示:

foo=0j0h0min0s

在不使用日期的情况下,在几秒钟内转换它的最佳方法是什么?
我试过这样的东西,听起来很不错,但运气不好:
#> IFS=: read -r j h min s <<<"$foo"
#> time_s=$((((j * 24 + h) * 60 + min) * 60 + s))
ksh: syntax error: `<' unexpected

任何想法都是受欢迎的,我只是不能使用date -d进行转换,因为它不存在于我正在工作的系统中。

最佳答案

<<<"$foo"主要是一种抨击主义。它在某些/更新的ksh中受支持。(google'ksh here string')。
您的读数试图在:处拆分,但您的输入中不存在wich
如果你先去掉字符,你可以在空白处拆分(通常是这样)
并将here字符串改为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<"

关于linux - 在ksh中分割字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48336804/

10-11 18:24