Linux – Tail, grep and count the instances found in one command

countgreplinuxtail

I am tailing a files output and grepping for lines with certain data. I don't want to output the data to the screen but instead count the number of instances it found and send that to the screen. The number of instances can be scrolling and incrementing or it can overwrite existing and only show it as it increments higher. That part is not really important I just need a running count of instances found.

My command right now is

tail -f logfile | grep 'data I want'

I have tried using grep -c and wc -l but nothing have given me the results I am after. This particular Linux distro does not have pv and will not be able to get it. Is there a way I can do this?

Best Answer

GNU awk can do this fairly easily.

Rolling output:

tail -f logfile | grep 'stuff to grep for' | awk '{++i;print i}'

You can also leave out the grep and use awk's regular expressions instead:

tail -f logfile | awk '/stuff to grep for/ {++i;print i}'

For a single line output you can prepend a CR make it start at the front of the line again (works on a console):

tail -f logfile | awk '/stuff to grep for/ {++i;printf "\r%d",i}'
Related Topic