bash – 尾部-f输出的连续处理

前端之家收集整理的这篇文章主要介绍了bash – 尾部-f输出的连续处理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个文件,其中连续附加数字:
  1. 1
  2. 2
  3. 3
  4. 4

我想连续地计算它们的平均值,即:

  1. 1
  2. 1.5
  3. 2
  4. 2,5

我不想定期检查文件,我想以tail -f方式工作 – 只要附加一行,我就执行平均计算.

可能吗?

UPD问题移至https://stackoverflow.com/questions/9400306/countinuous-processing-of-tail-f-output

是.将tail -f管道传递给处理平均值的脚本.管道永远不会关闭,脚本可以立即处理它接收到的每一行……它将阻塞直到出现一条线.

此外,应该记住,可以计算运行平均值,而无需每次都添加所有值.我已经看到它,我觉得有必要提一下.

  1. #generator.pl
  2. $| = 1; #immediate flush
  3. while (1) {
  4. print int rand(100),"\n";
  5. sleep 1;
  6. }
  1. #average.pl
  2. $| = 1; #immediate output flush
  3. my $average = 0;
  4. my $count = 0;
  5. while (<>) {
  6. $average = ($average * $count + $_) / ($count + 1);
  7. $count++;
  8. print $average,"\n";
  9. }
  1. $perl generator.pl > source &
  2. [2] 15564
  3. (reverse-i-search)`': ^C
  4. $tail -f source | perl average.pl
  5. 54
  6. 28
  7. 27.6666666666667
  8. 35
  9. 41

而且,只是为了笑容:

  1. $tail -f source | awk '{total+=$0; count+=1; print total/count}'

这也有即时反馈.在我看来,你的问题是正在写入尾部正在读取的文件的应用程序缓冲.

有关该信息,请参阅http://www.pixelbeat.org/programming/stdio_buffering/.

猜你在找的Bash相关文章