Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color regex matches - without dropping misses

Tags:

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:

  • fred
  • ted
  • red
  • lead

Regex:

  • ".*red"

OUTPUT:

  • fred ( in red )
  • ted
  • red ( in red )
  • lead

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!

like image 897
mmocny Avatar asked Oct 27 '08 20:10

mmocny


2 Answers

The simplest solution would be to use egrep --color=always 'text|^' which would match all line beginnings but only color the desired text.

like image 158
crenate Avatar answered Sep 30 '22 18:09

crenate


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

like image 34
Pawel Wiejacha Avatar answered Sep 30 '22 19:09

Pawel Wiejacha