20

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?

1
  • 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) Commented Dec 25, 2013 at 15:50

2 Answers 2

28

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

3
  • 1
    Have you tested it? This is what I see in the output: ^[[32mword^[[0m Commented Dec 25, 2013 at 7:15
  • @Meysam Sorry, ^[ is how the escape character is represented at least under vi, answer updated to avoid the ambiguity. Commented Dec 25, 2013 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 Commented Nov 20, 2017 at 5:09

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.