我有一个文件,其中数字不断被添加:
1
2
3
4
我想计算它们的平均值,而且是连续的,即:
1
1.5
2
2,5
我不想定期检查文件,我希望以tail -f的方式工作 - 只要有一行被追加,我就进行平均值计算。 是否可能? PS 尝试过tail -f file.txt | awk '{total+=$0;count+=1;print total/count}',但没有输出,卡住了。
你可能会遇到缓冲问题。也许适合你的解决方案是:
perl -wne 'BEGIN{ $| = 1 } $t += $_; print $t / $. . "\n"; '
$| = 1 关闭缓冲,其余部分与您的 awk 脚本相同。
Tcl非常适合这种事件驱动的编程。假设您的PATH中有tclsh
:
#!/usr/bin/env tclsh
proc calculate_running_mean {chan} {
gets $chan line
if {[string is integer -strict $line]} {
incr ::sum $line
incr ::count 1
puts [expr {1.0 * $::sum / $::count}]
}
}
set filename numbers.txt
set fid [open $filename r]
fileevent $fid readable [list calculate_running_mean $fid]
vwait forever