views:

543

answers:

3

I'm using grep from the command line via cygwin. I'm wondering if there's any way to get it to highlight the part of each line that matches the regex. The closest thing I'm seeing is the -o option, but that only outputs the matching area, and I'd like to see the entire line.

+7  A: 

Try the --color switch.

Dave Costa
Wow. now sure how I missed that. One extra question. Is there any way to maintain the color when chaining greps? I have one grep to search, piped to a second one to filter out some matches I don't want to see. Any way to maintain the color from the first grep?
Herms
I have updated my answer with a possible way you could do that.
Paul Dixon
+10  A: 

Take a look at the --color (or --colour) option, e.g.

grep --color POST access_log

By default, this uses the "auto" mode which only includes the color codes when output to a terminal, but not when you pipe the output elsewhere. If you want the colors piped out to something other than stdout, then use --color=always

See the linked article for ways you can change the colour and make grep use this option by default.

Paul Dixon
I added the --color=always, but that seems to break the chained greps, probably because the color control chars are being picked up by the regexes. The fix I came up with was to just repeat the first grep in the chain at the very end, with the --color option. I lose the coloring of the file names, but it still colors the match, which is the important part.
Herms
+3  A: 

You might want to try the ack tool. It does the highlighting by default, iirc.

Actually, it does many usefull things by default. Some people like it and I hope You will too.

Reef