About nixCraft

Topics

Quick tip: Easily find strings with grep color highlighting feature

Posted by Vivek Gite [Last updated: October 11, 2007]

grep command is the de facto tool for searching text files. However when there are too many matches, it can be difficult to find the requested text in the search results. grep comes with --color='auto' option. It surrounds the matching string with the colour, thus resulting enhanced output.

Finding string with color highlighting

Pass --color option to grep command:
# grep --color='auto' -i error /var/log/messages
Output:

............
...
Oct  9 16:12:14 vivek-desktop kernel: [   11.555442] bt878: probe of 0000:05:00.1 failed with error -22
Oct 10 17:35:28 vivek-desktop kernel: [   10.564710] bt878: probe of 0000:05:00.1 failed with error -22
Oct 11 10:15:34 vivek-desktop kernel: [   12.187477] bt878: probe of 0000:05:00.1 failed with error -22
Oct 11 14:29:56 vivek-desktop kernel: [   11.135309] bt878: probe of 0000:05:00.1 failed with error -22
..........
...
....

Now all matched text displayed using red color. The --color option to matches in the input in red color by default. Color is added via ANSI escape sequences. To change color use environment variable GREP_COLOR. Following will set background to red and foreground to white:
$ export GREP_COLOR='1;37;41'
$ egrep --color=auto -i '(error|fatal|warn|drop)' /var/log/messages

Output:
Quick tip: Easily find strings with gep color highlighting feature
I recommend putting following in ~/.bash_profile OR ~/.bashrc file:
$ vi ~/.bash_profile
Append following alias:
export GREP_COLOR='1;37;41'
alias grep='grep --color=auto'

Save and close the file. Please note that --color option works with many GNU text utilities, so feel free to use the same.

Tell us how we're doing: Please answer a few questions about your experience to help us improve nixCraft.

You may also be interested in other helpful articles:

Discussion on This Article:

  1. BvTaa Says:

    Nice tip, thanks a lot!

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Tags: , , , ,

Copyright © 2004-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.