Highlight Text in Bash

We want to highlight like grep, but we do not want to filter out unmatched lines. Very nice for tailing logs! We what something like this:

bash text highligt

The quick and the dirty…

Use grep to match the start of every line (^) or “some” text. B in this case.

% printf "A\nB\nB\nC\n" | grep --color=always -E "^|B"
A
B
B
C

Adding in colors

Yellow! Set the grep highlight color using the GREP_COLORS environment variable.

% printf "A\nB\nB\nC\n" | env GREP_COLORS="ms=1;33" grep --color=always -E "^|B"
A
B
B
C

Stacking greps

When greping another grep output. To stop grep buffering in a pipe, add the --line-buffered option.

% printf "A\nB\nB\nC\n" | env GREP_COLORS="ms=1;33" grep --color=always -E "^|B" |env GREP_COLORS="ms=1;34" grep --color=always -E "^|A"
A
B
B
C

Putting it all together

To produce the screenshot at the top of the page we can roll this into a nice bash script with cli args and color names :bowtie:. Here is the usage output:

usage: /usr/local/bin/highlight [-c <color>] regex
  options:
    -c color    Color to highlight regex matches with

Valid colors: black,blue,green,cyan,red,purple,brown,lightgray,darkgray,lightblue,lightgreen,lightcyan,lightred,lightpurple,yellow,white

And the full script here.