Thursday, March 31, 2011

Highlight lines in stdout/stderr containing a pattern

So you have lots of log lines flying by on stdout, but some of them are much more important than others. It's not always easy to identify which lines you should be paying attention to. One solution is to grep for patterns and then use color to draw your attention to the important part:


# Show only matching lines from stdout and stderr, with 5 surrounding lines

$ ./verboseProgram |& grep -C5 --color=yes "ERROR"

-or-

# Redirect stdout and stderr to a file while also printing them to screen
$ ./verboseProgram |& tee log
# Then do the same matching post-mortem
$ grep -C5 --color=yes "ERROR" log


Another solution is to highlight the lines matching patterns you care about without discarding everything else. This can be done using the following bash/awk script:

## highlight.sh ##

#!/usr/bin/env bash                                                                                                                          
set -ueo pipefail


pattern=$1
awk '{if(/'$pattern'/){print "\033[1;31m"$0"\033[0m"}else{print}}'
###############

Then you can run your program, keep a log file, and still not miss things as they arrive:
$ ./verboseProgram |& tee log | highlight.sh "ERROR"

If you're not a fan of red, you can pick your favorite color from: http://en.wikipedia.org/wiki/ANSI_escape_code

No comments:

Post a Comment