Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

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.

1  
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 Answers 2

up vote 3 down vote accepted

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
share|improve this answer
    
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
    
@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:

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.

share|improve this answer
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
    
Great! Thank you. –  Meysam Dec 25 '13 at 9:40

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