我有一个文件,其中连续附加数字:
- 1
- 2
- 3
- 4
我想连续地计算它们的平均值,即:
- 1
- 1.5
- 2
- 2,5
我不想定期检查文件,我想以tail -f方式工作 – 只要附加一行,我就执行平均计算.
可能吗?
UPD问题移至https://stackoverflow.com/questions/9400306/countinuous-processing-of-tail-f-output
是.将tail -f管道传递给处理平均值的脚本.管道永远不会关闭,脚本可以立即处理它接收到的每一行……它将阻塞直到出现一条线.
此外,应该记住,可以计算运行平均值,而无需每次都添加所有值.我已经看到它,我觉得有必要提一下.
- #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/.