Linux Coloring of the Results
When reviewing a UNIX log file, I often feel like I’m looking for a needle in a haystack. Even after I ‘grep’ out what I’m looking for I still can’t find it. I also like to use the ‘tail –f’ command to watch a rolling log, but again the information scrolls too fast and you just can’t find what you’re looking for in the quick moving results. To find the interesting information we will obviously use the ‘grep’ command, but to identify the results in the information there are a couple of methods.
The ‘grep’ command will support ANSI colorization and this can be done a number of ways. The first way is to specify the –color or –colour option on the command line. The second way is to export a variable that ‘grep’ looks at when executed. You will most likey want to add the export lines to your .profile or .bashrc file.
cat {somelogfile} | grep --color {matching text} or tail -f {somerollinglog} | grep --color {matching text} export GREP_OPTIONS="--color=auto" export GREP_COLOR='1;31'
Grep colorization is good, but sometimes you need to see all the lines from the log file and focus on just what you are looking for. In this case we need to take a different approach; grep will filter and show just the lines that contain the information matching the regular expression we’ve feed it. In order to see all the lines and only highlight the specific pieces we want to see, we will need to run the information thru a mechanism that will highlight just the matching piece. I originally came across this poorly written piece of PERL script that I adapted and refined over many iterations.
#!/usr/bin/perl ### Bohack 2006i ### Usage: hilite <ansi_command> <target_string> ### Purpose: Will read text from standard input and perform specified highlighting ### command before displaying text to standard output. ### License: GNU GPL $|=1; # don't buffer i/o $target = "$ARGV[0]"; $color = "\e[31m"; $end = "\e[0m";while(<STDIN>) { s/($target)/$color$1$end/i; print $_; }
Remeber to chmod the file for execute permissions and put it in the path. (i.e. chmod 0777 hilite)
cat {somelogfile} | hilite {matching text} or tail -f {somerollinglog} | hilite {matching text}
Tags: Linux