Skip to main content
1 of 3
DrBeco
  • 811
  • 8
  • 23

OP asked for grep, and that is what I RECOMMEND; but after trying hard to solve a problem with sed, for the record, here is a simple solution with it:

sed $'s/main/\E[31m&\E[0m/g' testt.c 

or

cat testt.c | sed $'s/main/\E[31m&\E[0m/g' 

Will paint main in red.

  • \E[31m : red color start sequence
  • \E[0m : finished color mark
  • & : the matched pattern
  • /g : all words in a line, not just the first
  • $'string' is bash strings with escaped characters interpreted

Regarding grep, it also works using ^ (begin of line) instead of $ (end of line). Example:

egrep "^|main" testt.c 

And just to show this crazy alias that I DO NOT RECOMMEND, you can even let the open quotes:

alias h='egrep -e"^|' h main" testt.c cat testt.c | h main" 

all work! :) Don't worry if you forget to close the quote, bash will remember you with a "continuing line character".

DrBeco
  • 811
  • 8
  • 23