Home > Bash, linux, Tip > grep in real time

grep in real time

By combining tail and grep you can achieve something pretty cool. First let’s write this simple bash script:

#!/bin/bash
[ $# -lt 2 ] && echo "$0 file \"pattern\"" && exit 0
tail -f $1|while read line; do echo $line|egrep --color "$2"; done

Save it as flowgrep, make it executable:

chmod +x flowgrep

The syntax is very easy, just ./flowgrep <log_file> <pattern>. Let’s monitor a growing log file for numbers:

./flowgrep event.log [0-9]+

This will output lines containing at least one 1-digit number and the number(s) will be in red. To terminate the script simply press Ctrl + C

Sample output:

123 is a good number

July 4th is a few days away.

I feel it’s 82 degrees right now.

^C

Note: if pattern contains space(s), use double quotations (“) to enclose it. for example:

./flowgrep /var/log/messages "Too many login failures"

Advertisements
Categories: Bash, linux, Tip
  1. July 14, 2009 at 7:53 am

    Thanks, it´s helpfully

    • ricoch3n
      July 14, 2009 at 12:42 pm

      Thanks krkorb. Glad it is of help.

  2. sgijoe
    October 29, 2009 at 4:38 pm

    good stuff!

  1. July 13, 2009 at 6:58 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: