Skip to content

Instantly share code, notes, and snippets.

@melissaboiko
Created July 6, 2012 15:41
Show Gist options
  • Save melissaboiko/3060976 to your computer and use it in GitHub Desktop.
Save melissaboiko/3060976 to your computer and use it in GitHub Desktop.
simple script to color matching lines (like grep --color, but also prints non-matching lines)
#!/bin/bash
pname="$(basename $0)"
function usage()
{
echo "Usage: $pname [OPTIONS] PATTERN [FILES and/or GREP_OPTIONS...]
Colorize all matches for PATTERN, an extended regular expression.
Non-matching lines are still printed.
This is a wrapper over grep -E. See grep(1) for details of extended
regular expression syntax. The mandatory argument PATTERN acts as
a separator; everything after it is passed to grep as-is.
Examples:
my_command | $pname my_pattern
my_command | $pname -c red pattern1 | $pname -c green pattern2
$pname -c4 -u -b my_pattern my_file -i
Options:
-b: match is printed bold/bright
-u: match is underlined
-b: match blinks
-i: match is printed in inverse color
-c [ANSICOLOR]: match is printed in the given foreground color
-g [ANSICOLOR]: match is printed in the given background color
-d: prints resulting grep command (for debugging)
ANSICOLOR can be numeric or a color name; valid values are:
0 1 2 3 4 5 6 7
black red green yellow blue magenta cyan white
Notice that some colors change hues when bold/bright.
"
exit
}
sgr=''
debug=''
while getopts 'bulic:g:dh' option; do
case $option in
# bold/bright
b) sgr="$sgr;1";;
# underline
u) sgr="$sgr;4";;
# blink
l) sgr="$sgr;l";;
# inverse
i) sgr="$sgr;7";;
# foreground color
c)
case "$OPTARG" in
0|black) sgr="$sgr;30";;
1|red) sgr="$sgr;31";;
2|green) sgr="$sgr;32" ;;
3|yellow) sgr="$sgr;33" ;;
4|blue) sgr="$sgr;34" ;;
5|magenta) sgr="$sgr;35" ;;
6|cyan) sgr="$sgr;36" ;;
7|white) sgr="$sgr;37" ;;
esac
;;
# background color
g)
case "$OPTARG" in
0|black) sgr="$sgr;40";;
1|red) sgr="$sgr;41";;
2|green) sgr="$sgr;42" ;;
3|yellow) sgr="$sgr;43" ;;
4|blue) sgr="$sgr;44" ;;
5|magenta) sgr="$sgr;45" ;;
6|cyan) sgr="$sgr;46" ;;
7|white) sgr="$sgr;47" ;;
esac
;;
d) debug=1;;
h|*) usage;;
esac
done
if [ "$sgr" ]; then
# remove first spurious ';'
sgr="${sgr:1}"
# default as of GNU grep 2.6.3, but changing ms= and mc= .
# see man grep for details.
export GREP_COLORS="ms=$sgr:mc=$sgr:sl=:cx=:fn=35:ln=32:bn=32:se=36"
fi
shift $((OPTIND-1))
if ! [ "$1" ]; then
echo "Error: PATTERN argument is mandatory."
echo
usage
fi
# "|$" grep trick as described in
# http://stackoverflow.com/questions/981601/colorized-grep-viewing-the-entire-file-with-highlighting
pattern="$1|$"
shift 1
[ $debug ] && set -x
grep -E --color=yes "$pattern" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment