使用shell / awk脚本添加时间戳

时间:2019-02-01 11:28:46

标签: shell

我在文本文件中有以下数据,即时间字段:00:26:15

00:01:33
00:02:20
00:04:33
00:00:45
00:01:33
00:02:16
00:06:29
00:08:16
00:26:15
00:01:33
00:02:20
00:04:33
00:00:45
00:01:33
00:02:16
00:06:29
00:08:16  

如何添加它们并使用awk或shell获取平均值?

输出应为总时间= $ total 平均时间= $ avg

2 个答案:

答案 0 :(得分:0)

将这些时间保存到“文件”,然后运行以下命令:

cat file | tr "\n" " " | tr -s " " | awk -F ' ' '{ for(a = 1; a <= NF; a ++){ split($a, t, ":"); total += t[1]*3600 + t[2]*60 + t[3] } a = total/NF; printf("%02d:%02d:%02d\n", a/3600, a%3600/60, a%3600%60) }'

第一个命令将读取'file',第二个命令将删除换行符。 Awk会将这些时间与stdin分开,汇总秒数,最后将secknds转换为%H:%M:%S格式。

答案 1 :(得分:0)

将列表保存到文件file中:

cat <<EOF >file
00:01:33
00:02:20
00:04:33
00:00:45
00:01:33
00:02:16
00:06:29
00:08:16
00:26:15
00:01:33
00:02:20
00:04:33
00:00:45
00:01:33
00:02:16
00:06:29
00:08:16
EOF

我可以做到以下几点:

# convert each line to seconds. using stream and date.
to_seconds=$(<file xargs -i date -d"1970-01-01 {}Z" +%s)
# sum of seconds
sum=$(<<<"$to_seconds" tr '\n' '+' | sed 's/+$/\n/' | bc)
# convert seconds into HH:MM:SS
sec_to_time() { echo "$(($1/3600)):$(($1%3600/60)):$(($1%60))"; }
sum_time=$(sec_to_time "$sum")
# number of lines in the file
lines=$(<file wc -l)
# avarage is the sum divided by the number of lines
avg=$(<<<"$sum / $lines" bc)
# convert avg into time
avg_time=$(sec_to_time "$avg")
# output
echo "sum $sum_time"
echo "avg $avg_time"

我将输出:

sum 1:21:45
avg 0:4:48

我们还可以使用一些tee和同步功能来制作高级的oneliner:

exec 3<> >(:)
avg=$(
        # convert to seconds
        <file xargs -i date -d"1970-01-01 {}Z" +%s |
        # calculate the sum
        tr '\n' '+' | sed 's/+$/\n/' | bc |
        # tee - output sum to 3 file descriptor
        tee >(sec_to_time "$(cat)" >&3) |
        # calculate avarage and convert to time
        echo "$(cat) / $(<file wc -l)" | bc | 
        sec_to_time "$(cat)"
)
# just to be sure, timeout the background job with a... timeout
sum=$(timeout 1 head -n1 <&3)
exec 3<&-