计算 bash 中两个时间(包括磨秒)之间的差值



我有一个简单的bash脚本,每行输出两个时间戳,如下所示:

10:25:48,192 10:25:46,967
10:25:48,522 10:25:48,200
10:25:49,418 10:25:48,531

我想优化脚本以计算每行上两个时间戳之间的差异(以毫秒为单位(。如何做到这一点?

#!/bin/bash
declare -i d1 d2 diff    # set integer flag
while IFS=":, " read -r h1 m1 s1 x1 h2 m2 s2 x2; do
  # force decimal numbers without leading zeros and calculate milliseconds
  d1=$((10#$h1))*60*60*1000+$((10#$m1))*60*1000+$((10#$s1))*1000+$((10#$x1))
  d2=$((10#$h2))*60*60*1000+$((10#$m2))*60*1000+$((10#$s2))*1000+$((10#$x2))
  diff=$d1-$d2
  echo $diff
done < file

输出:

1225322887

与awk:

awk -F '[:, ]' '{print ($1*60*60*1000+$2*60*1000+$3*1000+$4)-($5*60*60*1000+$6*60*1000+$7*1000+$8)}' file

最新更新