我有一个文件,数字不断追加:
1 2 3 4
我想计算他们的意思,也是连续的,即:
1 1.5 2 2,5
我不想定期检查文件,我想以尾巴的方式工作 – 只要附加一行,我会进行平均值计算。
可能吗?
UPD问题转移到https://stackoverflow.com/questions/9400306/countinuous-processing-of-tail-f-output
是。 pipetail -f到处理你的平均的脚本。 pipe道永远不会closures,脚本可以立即处理它收到的每一行…它将阻塞,直到出现一行。
另外,应该记住,可以计算一个运行平均值,而不必每次都添加所有的值。 我已经看到这足够我觉得有必要提及它。
#generator.pl $| = 1; #immediate flush while (1) { print int rand(100), "\n"; sleep 1; }
#average.pl $| = 1; #immediate output flush my $average = 0; my $count = 0; while (<>) { $average = ($average * $count + $_) / ($count + 1); $count++; print $average, "\n"; }
$ perl generator.pl > source & [2] 15564 (reverse-i-search)`': ^C $ tail -f source | perl average.pl 54 28 27.6666666666667 35 41
而且,只是为了咧嘴笑:
$tail -f source | awk '{total+=$0; count+=1; print total/count}'
这也有即时的反馈。 在我看来,你的问题是由正在写入尾部正在读取的文件的应用程序缓冲。
有关这方面的信息,请参阅http://www.pixelbeat.org/programming/stdio_buffering/ 。
这是一个使用DC的简单解决scheme。
tail -f | dc -e '5k 0 d sc st [? lc 1 + sc lt + st lt lc / pc lax] sa lax'
我不确定dc是否支持尾recursion,如果不是这个程序会泄漏内存。 直stream有非常糟糕的文件。 🙂
什么,你不喜欢脑袋? 🙂
在Ruby中这是一个简单的解决scheme。 tail -f | ruby -e 'sum=total=0.0; while line=gets; total += line.to_f; sum += 1; puts total/sum; end'