如何根据时间戳将记录分组到存储桶中?

时间:2010-07-10 08:39:36

标签: shell timestamp grouping logging bucket

我有一份日志中的条目列表:

15:38:52.363 1031
15:41:06.347 1259
15:41:06.597 1171
15:48:44.115 1588
15:48:44.125 1366
15:48:44.125 1132
15:53:14.525 1348
15:53:15.121 1553
15:53:15.181 1286
15:53:15.187 1293

第一个是时间戳,第二个是值。

现在我试图将它们分组,比如20秒。我想要总结价值,或得到他们的平均值。我想知道最简单的方法是什么?我最好通过一些简单的shell脚本来做到这一点,所以我可以将我的grep语句输入并获得一个分开的列表。谢谢!

1 个答案:

答案 0 :(得分:1)

gawk脚本完全忽略小数秒。它对从一天到下一天(跨越00:00:00)的跨越也一无所知:

grep ... | awk -v interval=20 'function groupout() {print "----", "Timespan ending:", strftime("%T", prevtime), "Sum:", sum, "Avg:", sum/count, "----"} BEGIN {prevtime = 0} {split($1, a, "[:.]"); time = mktime(strftime("%Y %m %d") " " a[1] " " a[2] " " a[3]); if (time > prevtime + interval) {if (NR != 1) {groupout(); sum=0; count=0}}; print; sum+=$2; count++; prevtime = time} END {groupout()}'

输出:

15:38:52.363 1031
---- Timespan ending: 15:38:52 Sum: 1031 Avg: 1031 ----
15:41:06.347 1259
15:41:06.597 1171
---- Timespan ending: 15:41:06 Sum: 2430 Avg: 1215 ----
15:48:44.115 1588
15:48:44.125 1366
15:48:44.125 1132
---- Timespan ending: 15:48:44 Sum: 4086 Avg: 1362 ----
15:53:14.525 1348
15:53:15.121 1553
15:53:15.181 1286
15:53:15.187 1293
---- Timespan ending: 15:53:15 Sum: 5480 Avg: 1370 ----

这里再次更可读:

awk -v interval=20 '
function groupout() {
    print "----", "Timespan ending:", strftime("%T", prevtime), "Sum:", sum, "Avg:", sum/count, "----"
}
BEGIN {
    prevtime = 0
} 
{
    split($1, a, "[:.]"); 
    time = mktime(strftime("%Y %m %d") " " a[1] " " a[2] " " a[3]); 
    if (time > prevtime + interval) {
        if (NR != 1) {groupout(); sum=0; count=0}
    }; 
    print; 
    sum+=$2; 
    count++; 
    prevtime = time
} 
END {groupout()}'