This question already has an answer here:

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?

marked as duplicate by manatwork, Anthon, slm, l0b0, Gilles Dec 25 '13 at 19:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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

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
  • Thank you. The highlighted word is currently red on my computer. Is it possible to customize the color as well? – Meysam Dec 25 '13 at 6:20
  • 1
    @Meysam You can do so using the GREP_COLOR(S) environment variable. gnu.org/software/grep/manual/html_node/… – Chris Down Dec 25 '13 at 6:24

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

  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.

  • 1
    Have you tested it? This is what I see in the output: ^[[32mword^[[0m – Meysam Dec 25 '13 at 7: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 9:19
  • Question closed, so here is a one-liner solution: cat testt.c | sed $'s/main/\E[31m&\E[0m/g' Hope it helps – Dr Beco Nov 20 '17 at 5:09

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