Colorized grep -- viewing the entire file with highlighted matches

Solution 1:

Here are some ways to do it:

grep --color 'pattern\|$' file
grep --color -E 'pattern|$' file
egrep --color 'pattern|$' file

The | symbol is the OR operator. Either escape it using \ or tell grep that the search text has to be interpreted as regular expressions by adding -E or using the egrep command instead of grep.

The search text "pattern|$" is actually a trick, it will match lines that have pattern OR lines that have an end. Because all lines have an end, all lines are matched, but the end of a line isn't actually any characters, so it won't be colored.

To also pass the colored parts through pipes, e.g. towards less, provide the always parameter to --color:

grep --color=always 'pattern\|$' file | less -r
grep --color=always -E 'pattern|$' file | less -r
egrep --color=always 'pattern|$' file | less -r

Solution 2:

Here's something along the same lines. Chances are, you'll be using less anyway, so try this:

less -p pattern file

It will highlight the pattern and jump to the first occurrence of it in the file.

You can jump to the next occurence with n and to the previous occurence with p. Quit with q.

Solution 3:

I'd like to recommend ack -- better than grep, a power search tool for programmers.

$ ack --color --passthru --pager="${PAGER:-less -R}" pattern files
$ ack --color --passthru pattern files | less -R
$ export ACK_PAGER_COLOR="${PAGER:-less -R}"
$ ack --passthru pattern files

I love it because it defaults to recursive searching of directories (and does so much smarter than grep -r), supports full Perl regular expressions (rather than the POSIXish regex(3)), and has a much nicer context display when searching many files.

Solution 4:

You can use my highlight script from https://github.com/kepkin/dev-shell-essentials

It's better than grep because you can highlight each match with its own color.

$ command_here | highlight green "input" | highlight red "output"

Screen shot from Github project