6

I want to view text (could be a file or a piped command output) in the terminal, but I would like to highlight a specific pattern in the text with colors, similarly to how grep highlights the pattern match in its output lines.

The reason why I can't use standard grep "pattern" /path/to/file here is because I want to view the entire text (ideally scrollable as if piped through less) and not just the lines containing the pattern.

  • 1
    grep --color -E "test|$" yourfile – Android Dev Aug 9 '16 at 23:37
  • Oops, sorry. Had a typo in it. It surprisingly works. Please post as answer @AndroidDev :) – Byte Commander Aug 9 '16 at 23:39
  • Certainly! I'll also include sample output. – Android Dev Aug 9 '16 at 23:42
  • 1
    @ByteCommander try the -r or -R switch e.g. grep --color=always -E "test|$" yourfile | less -R – steeldriver Aug 9 '16 at 23:51
  • 1
    @steeldriver Thanks, that works. But it requires the grep --color=always, just grep --color is not enough. – Byte Commander Aug 9 '16 at 23:56
7

Actually, this can be done very easily with some grep parameters.

The magic command you are looking for is:

grep --color -E "test|$" yourfile

Here's some sample output: enter image description here


Full disclosure: That command was taken from this answer.

  • You could include @steeldriver's approach to pipe it through less while preserving colors into your answer. And it would be nice to see an explanation of the command. – Byte Commander Aug 9 '16 at 23:57
  • @ByteCommander - I'll do that a bit later this evening. Have to do something else ATM :) – Android Dev Aug 10 '16 at 0:05
  • 1
    It's basically matching a zero-length expression that occurs in every line; because it occurs in every line, every line is output; but because it has zero length, the match isn't highlighted. As well as PATTERN|$ you could use ^|PATTERN or even just |PATTERN (since the empty pattern matches all lines as well). – steeldriver Aug 10 '16 at 0:10
4

If you're not stuck on color highlighting, you could use less itself e.g.

less +g -p PATTERN file

or

less +g +/PATTERN file

The +/PATTERN highlights all instances of PATTERN in file, and the +g suppresses the default behavior of scrolling to the first match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.