18

I can do the following to see if some word is available in the output of "cat":

cat filename | grep word

This filters the output and shows only those lines which contain "word". Now, is it possible to only highlight the "word" in the output, without dropping other lines?

B Faley
  • 4,213
  • 11
  • 37
  • 48
  • 2
    `grep word filename` is clearer and faster. ;) Also, `less` can do this while also providing paging. Just search for `word` by typing `/word` (the term is actually a regular expression, just like `grep`) – Alexios Dec 25 '13 at 15:50

2 Answers2

26

You can grep for an EOL along with your real query (if you already have an alias for grep to use --color, as is default in many distributions, you can omit it in the following examples):

grep --color=auto 'word\|$' file

Since the EOL is not a real character, it won't highlight anything, but it will match all lines.

If you would prefer not to have to escape the pipe character, you can use extended regular expressions:

grep -E --color=auto 'word|$' file
Chris Down
  • 122,090
  • 24
  • 265
  • 262
  • Thank you. The highlighted word is currently red on my computer. Is it possible to customize the color as well? – B Faley Dec 25 '13 at 06:20
  • 1
    @Meysam You can do so using the `GREP_COLOR(S)` environment variable. http://www.gnu.org/software/grep/manual/html_node/Environment-Variables.html – Chris Down Dec 25 '13 at 06:24
  • Would you mind editing the answer to provide a function for this? I'd love to have `hl` ("highlight") declared in my `.zshrc`. Something like `cat foo.txt | hl bar`. But it should also work when provided a file (`hl "bar" foo.txt`). – payne Nov 08 '22 at 18:26
6

If you haven't GNU grep available, here is something more portable:

grepc()
{
  pattern=$1
  shift
  esc=$(printf "\033")
  sed 's"'"$pattern"'"'$esc'[32m&'$esc'[0m"g' "$@"
}

You can customize the color using one of these codes

30m black
31m red
32m green
33m yellow
34m blue
35m magenta
36m cyan
37m white

Using 7m instead of a color code will put the string in reverse video.

jlliagre
  • 60,319
  • 10
  • 115
  • 157
  • 1
    Have you tested it? This is what I see in the output: `^[[32mword^[[0m` – B Faley Dec 25 '13 at 07:15
  • @Meysam Sorry, `^[` is how the escape character is represented at least under `vi`, answer updated to avoid the ambiguity. – jlliagre Dec 25 '13 at 09:19
  • Question closed, so here is a one-liner solution: `cat testt.c | sed $'s/main/\E[31m&\E[0m/g'` Hope it helps – DrBeco Nov 20 '17 at 05:09