Let's give grep some colour

  |   Source

For those using GNU/Linux, grep is a fundamental utility. If you're looking for a word into a file with very long lines, how could you find the result of your search immediately? It's difficult. That's why we're going to give grep some fancy mood ;-)

First of all, let's open ~/.bashrc (or the corresponding file, if you use another shell than BASH), and put, in any point (better if at the end of the file), the following lines:

alias grep="grep --color=auto"

export GREP\_COLOR="1;33;40"

After this, let's go back to the shell and give the command source ~/.bashrc, so as to enable the new settings.

And now, the explanation. The first line tells Bash to substitute to "grep" the command "grep --color=auto". This lets grep consider the environment variable GREP_COLOR. In fact, in the second line, we export this variable with the colour we want. The "colour" format is:

  • attr is the "attribute" for the highlighted text, it can be 0 **(normal**), **1 (bold) **and so on;
  • foreground is the foreground colour of the text, and can be:

System Message: WARNING/2 (<string>, line 25)

Bullet list ends without a blank line; unexpected unindent.
  • 30 - black
  • 31 - red
  • 32 - green
  • 33 - yellow
  • 34 - blue
  • 35 - magenta
  • 36 - cyan
  • 37 - white
  • background is the background colour, and can have values of:

System Message: WARNING/2 (<string>, line 35)

Bullet list ends without a blank line; unexpected unindent.
  • 40 - black
  • 41 - red
  • 42 - green
  • 43 - yellow
  • 44 - blue
  • 45 - magenta
  • 46 - cyan
  • 47 - white

So the example written above sets the searched text in bold, in yellow with a black background. It shines on my black shell! ;-)

Enjoy grep!

Comments powered by Disqus
Contents © 2013 David Paleino - Powered by Nikola