簡體   English   中英

尾部-f輸出的連續處理

[英]Coutinuous processing of tail -f output

我有一個文件,其中連續附加數字:

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}' 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM