glaz666
glaz666

Reputation: 8721

Coutinuous processing of tail -f output

I have a file where numbers are continuously appended:

1
2
3
4

I want to calculate their mean, also continuously, i.e.:

1
1.5
2
2,5

I don't want to check file periodically, I want to it in the manner tail -f work - as soon as a line is appended, I perform mean calculations.

Is it possible?

PS Tried tail -f file.txt | awk '{total+=$0;count+=1;print total/count}' but it hangs without output

Upvotes: 3

Views: 502

Answers (2)

glenn jackman
glenn jackman

Reputation: 246744

Tcl is great for this kind of event driven programming. Assuming you have a tclsh in your PATH:

#!/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

Upvotes: -1

William Pursell
William Pursell

Reputation: 212158

You are going to run into buffering issues. Perhaps a solution that will work for you is:

perl -wne 'BEGIN{ $| = 1 } $t += $_; print $t / $. . "\n"; '

The $| = 1 turns off buffering. The rest is the same as your awk script.

Upvotes: 2

Related Questions