I frequently use grep's context command line options (-A, -B, and -C), but occasionally I want to view the whole file with matching expressions highlighted. To accomplish this currently I simply specify -C 999999999, but this seems silly.

Is there an option within OS X's bundled grep that will allow me to easily take advantage of grep's matching and colorizing features, without hiding any file content?

  • 1
    I say "OS X's bundled grep" explicitly because I know that this is BSD grep, and I would rather not install GNU's whole coreutils, assuming GNU grep has this built in. – Jason Salaz Aug 3 '12 at 8:14
  • 1
    I don't think the bundled grep is capable of this. OTOH you could alias grep='/usr/bin/grep -C 999999999' in interactive shells and forget about it. – nohillside Aug 3 '12 at 9:21
  • 1
    This is not intended to be a permanent change :). (Translation: alias grepall='/usr/bin/grep -C 999999999') – Jason Salaz Aug 3 '12 at 9:29

I don't think there is any simple option in grep but this seems to work fine. From https://stackoverflow.com/a/981831

grep --color -E "pattern|$" file

The |$ at the end of the regular expression makes grep find pattern OR end of lines. It can't highlight those though, so just the pattern gets colored.

  • 1
    Also; -E "pattern.*|$" will highlight until the end of the line. – voices Apr 2 '16 at 15:54
  • For example: ls /bin/ /usr/bin/ |sort |grep --colour -nE '/.*|$' – voices Apr 2 '16 at 15:58

Assuming you want to read the file yourself, with the bits highlighted, less is the better tool for the job. less yourfile, type /, your pattern and hit return. n goes to the next match and space to the next page.

Alternatively, ack has a --passthru mode that does what you want. ack is so insanely useful it's worth looking into.

  • I love this answer, and may switch to ack eventually. But in the interim, grep is so insanely ingrained in my brain that it's a hard switch to make. But thank you for this wonderful alternative. – Jason Salaz Dec 19 '12 at 10:08

Setting -C to a negative integer seems to be equivalent to setting it an arbitrarily large number.

grep something --color -C -1 *.txt

But as with something like -C 9999999, if the file has multiple matches, some lines can be printed multiple times.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .