This question already has an answer here:
When using grep, it will highlight any text in a line with a match to your regular expression.
What if I want this behaviour, but have grep print out all lines as well? I came up empty after a quick look through the grep man page.
You can use my highlight script from https://github.com/kepkin/dev-shell-essentials
It's better than grep cause you can highlight each match with it's own color.
If you want to print "all" lines, there is a simple working solution:
Use ack. Checkout its
--passthru
option here: ack. It has the added benefit of allowing full perl regular expressions.You can also do it using grep like this:
This will match all lines and highlight the patterns. The
^
matches every start of line, but won't get printed/highlighted since it's not a character.(Note that most of the setups will use --color by default. You may not need that flag).
EDIT:
This works with OS X Mountain Lion's grep:
This is better than
'^|pattern1|pattern2'
because the^
part of the alternation matches at the beginning of the line whereas the$
matches at the end of the line. Some regular expression engines won't highlightpattern1
orpattern2
because^
already matched and the engine is eager.Something similar happens for
'pattern1|pattern2|'
because the regex engine notices the empty alternation at the end of the pattern string matches the beginning of the subject string.FIRST EDIT:
I ended up using perl:
This assumes you have an ANSI-compatible terminal.
ORIGINAL ANSWER:
If you're stuck with a strange
grep
, this might work:Adjust the numbers to get all the lines you want.
The second
grep
just removes extraneous--
lines inserted by the BSD-stylegrep
on Mac OS X Mountain Lion, even when the context of consecutive matches overlap.I thought GNU grep omitted the
--
lines when context overlaps, but it's been awhile so maybe I remember wrong.Since you want matches highlighted, this is probably for human consumption (as opposed to piping to another program for instance), so a nice solution would be to use:
And if you don't care about case sensitivity:
This also has the advantage of having pages, which is nice when having to go through a long output
You can do it using only grep by:
which gives you the following: