Graeme
Graeme

Reputation: 4602

Tailing less with a custom LESSOPEN colorize script

I've written the following script to pick out keywords from a log file and highlight terms:

#!/bin/bash
case "$1" in
    *.log) sed -e "s/\(.*\[Error\ \].*\)/\x1B[31m&\x1b[0m/" "$1" \
            | sed -e "s/\(.*\[Warn\ \ \].*\)/\x1B[33m&\x1b[0m/" \
            | sed -e "s/\(.*\[Info\ \ \].*\)/\x1B[32m&\x1b[0m/" \
            | sed -e "s/\(.*\[Debug\ \].*\)/\x1B[32m&\x1b[0m/" 
    ;;
esac

It works OK until I try and follow/tail less (Shift+F) at which point it fails to tail any new log lines. Any ideas why?

Upvotes: 2

Views: 385

Answers (1)

slebetman
slebetman

Reputation: 113974

That colorizes what you pass as an argument to the script. What you want instead is to read from stdin. Wrap your case statement in the following loop:

while read LINE; do
    case "$LINE" in
         # ...  rest of your code here
    esac
done

Now you can pipe it into your script:

tail -f somefile | colorize_script.sh

Additional answer:

I had this same need several years ago so I wrote a script that works like grep but colorizes the matching text instead of hiding non-matching text. If you have tcl on your system you can grab my script from here: http://wiki.tcl.tk/38096

Just copy/paste the code (it's only 200 lines) into an empty file and chmod it to make it executable. Name it cgrep (for color-grep) and put it somewhere in your executable path. Now you can do something like this:

tail -f somefile | cgrep '.*\[Error\s*\].*' -fg yellow -bg red

Upvotes: 2

Related Questions