When using grep --color=always
I can get pretty color highlighting for regex matches.
However, grep
only returns lines with at least one match. Instead, I am looking for a way to simply highlight regex matches, while leaving all other input alone, without dropping lines without any matches.
I have tried to get color working with sed
, and read the grep
documentation, but I can't seem to get what I want.
In case my description isnt obvious, I want:
INPUT:
Regex:
OUTPUT:
So that I could do:
list_stuff | color_grep "make_this_stand_out_but_dont_hide_the_rest"
EDIT:
I have found a solution, which isn't pretty, but it works:
Thanks to: http://www.pixelbeat.org/docs/terminal_colours/
Particularly the script (which I modified/simplified): http://www.pixelbeat.org/talks/iitui/sedgrep
function sedgrep () { C_PATT=`echo -e '\033[33;01m'` C_NORM=`echo -e '\033[m'` sed -s "s/$1/${C_PATT}&${C_NORM}/gi" }
Still looking for an easier way to do this!
The simplest solution would be to use egrep --color=always 'text|^'
which would match all line beginnings but only color the desired text.
Here is a script I use to colorize output.
I think I found the idea/snippet on some kind of blog or bash/sed tutorial - can't find it anymore, it was very long time ago.
#!/bin/bash red=$(tput bold;tput setaf 1) green=$(tput setaf 2) yellow=$(tput bold;tput setaf 3) fawn=$(tput setaf 3) blue=$(tput bold;tput setaf 4) purple=$(tput setaf 5) pink=$(tput bold;tput setaf 5) cyan=$(tput bold;tput setaf 6) gray=$(tput setaf 7) white=$(tput bold;tput setaf 7) normal=$(tput sgr0) sep=`echo -e '\001'` # use \001 as a separator instead of '/' while [ -n "$1" ] ; do color=${!1} pattern="$2" shift 2 rules="$rules;s$sep\($pattern\)$sep$color\1$normal${sep}g" done #stdbuf -o0 -i0 sed -u -e "$rules" sed -u -e "$rules"
Usage:
./colorize.sh color1 pattern1 color2 pattern2 ...
e.g.
dmesg | colorize.sh red '.*Hardware Error.*' red 'CPU[0-9]*: Core temperature above threshold' \ green 'wlan.: authenticated.*' yellow 'wlan.: deauthenticated.*'
Doesn't work well with overlapping patterns, but I've found it very useful anyway.
HTH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With