variable_2 - variable_1 = result
40:00:10.000 - 20:00:05.000 = 20:00:05.000
variable_2
始终更大而不是variable_1
基于这里的答案是现在正在运行的代码。
下面发布的代码计算了上面示例中两个变量(VARIABLE_1
和VARIABLE_2
)之间的时差,时间格式为 hh:mm:ss.ms 和将计算保存在变量RESULT
中的格式相同( hh:mm:ss.ms )。
VARIABLE_1_IN_MS=$( VARIABLE_1 | awk -F'[:]|[.]' '{print $1 * 60 * 60 * 1000 + $2 * 60 * 1000 + $3 * 1000 + $4}' )
VARIABLE_2_IN_MS=$( VARIABLE_2 | awk -F'[:]|[.]' '{print $1 * 60 * 60 * 1000 + $2 * 60 * 1000 + $3 * 1000 + $4}' )
DIFFERENCE_IN_MS=$(( VARIABLE_2_IN_MS - VARIABLE_1_IN_MS ))
RESIDUAL_DIFFERENCE_IN_MS=$DIFFERENCE_IN_MS
#Calculate *hours* in difference
HOURS_IN_MS=$(( RESIDUAL_DIFFERENCE_IN_MS - RESIDUAL_DIFFERENCE_IN_MS % (60*60*1000) ))
HOURS=$(( HOURS_IN_MS / (60*60*1000) ))
RESIDUAL_DIFFERENCE_IN_MS=$(( RESIDUAL_DIFFERENCE_IN_MS - HOURS_IN_MS ))
#Calculate *minutes* in difference
MINUTES_IN_MS=$(( RESIDUAL_DIFFERENCE_IN_MS - RESIDUAL_DIFFERENCE_IN_MS % (60*1000) ))
MINUTES=$(( MINUTES_IN_MS / (60*1000) ))
RESIDUAL_DIFFERENCE_IN_MS=$(( RESIDUAL_DIFFERENCE_IN_MS - MINUTES_IN_MS ))
#Calculate *seconds* in difference
SECONDS_IN_MS=$(( RESIDUAL_DIFFERENCE_IN_MS - RESIDUAL_DIFFERENCE_IN_MS % (1000) ))
SECONDS=$(( SECONDS_IN_MS / 1000))
RESIDUAL_DIFFERENCE_IN_MS=$(( RESIDUAL_DIFFERENCE_IN_MS - SECONDS_IN_MS ))
#Calculate *milliseconds* in difference
MILLISECONDS=$RESIDUAL_DIFFERENCE_IN_MS
RESULT="$HOURS:$MINUTES:$SECONDS.$MILLISECONDS"
答案 0 :(得分:1)
VARIABLE_1_IN_MS=$(echo "$VARIABLE_1" | awk -F':|.' '{print $1 * 60 * 60 * 1000 + $2 * 60 * 1000 + $3 * 1000 + $4}' )
VARIABLE_2_IN_MS=$(echo "$VARIABLE_2" | awk -F':|.' '{print $1 * 60 * 60 * 1000 + $2 * 60 * 1000 + $3 * 1000 + $4}' )
要将变量值传递给awk,请使用echo命令并添加$
&#39。严格来说,引用并不是必需的,但引用任何变量扩展以防止空格和通配符被误解是一个好主意。
DIFFERENCE_IN_MS=$(( VARIABLE_2_IN_MS - VARIABLE_1_IN_MS ))
应该注意的是,可以从$
内的变量引用中省略$((...))
,但这是少数几个上下文之一。 #39;是这样的。在正常使用情况下,您必须拥有$
个。如下作业:
RESIDUAL_DIFFERENCE_IN_MS=$DIFFERENCE_IN_MS