Keep a tally from a log file

I have a file called output.log which has this content:

Thread started
Thread finished
Thread started
Thread finished
Thread started
Thread started

I monitor its output using:

tail -f output.log

I’d like to write a command to keep a count of how many threads are running right now. For the case above, the output would be:

2 threads are running

Should I perhaps use grep and somehow keep a tally of the string instances?

Answer

You can use awk to do the counting. Though if nothing more complicated involved you can use

tail -f output.log | awk '/Thread started/{n++}/Thread finished/{n--} END { printf ("%d Threads are running\n", n)}' output.log

Better yet, use watch as follow:

watch -n.2 -x awk '/Thread started/{n++}/Thread finished/{n--} END { printf ("%d Threads are running\n", n)}' output.log

The -n.2 there will refresh every 0.2s as will appear on the top of the screen.

Attribution
Source : Link , Question Author : Fidel , Answer Author : Valentin Bajrami

Leave a Comment