Grep –line-buffered until X lines

grep

I'm watching a log and want to detect once a program has had 3 failed attempts:

tail -f file.log | grep --line-buffered program\ failed\ string

If the line count from grep hits 3 I want to return an error.

How can I do this?

Best Answer

awk is a great tool for scanning streams.

I assumed it should display all lines to see the log until it exit, contrary to your example with grep which display only error lines.

tail -f file.log | awk '
    BEGIN {
        count = 0
    }

    {
        print($0)

        if ($0 ~ /program failed/) {
            count++
            if (count == 3) {
                exit(1)
            }
        }
    }
'

You can move the awk code to tail.awk and call tail -f file.log | awk -f tail.awk if you prefer.

Equivalently, in a more compact form:

tail -f file.log | awk '1; /program failed/ && ++count == 3 { exit 1 }'
Related Question