AddThis

Tuesday, February 5, 2013

Grep And Less -- In COLOR

I grep a lot; but sometimes, I only have a vague idea of what I'm looking for, so my results can be looong.  So I typically pipe it into less and boom, I can page through it.  But when I do this, I always lose my coloring :(

But I ran into this neat little trick today:

Before (old way I used to do it):
grep foo * --color | less

Now:
grep foo * --color=always | less -R

Tada!  Ok so a little explanation.  The color option (turned off by default, which is why we included the flag) actually has three possible values you can assign to it.
1.  color=never - Pretty self explanatory
2.  color=always - Always include the special control characters to color the text
3.  color=auto - Include the special control characters unless you are piping to something or redirecting to a file

So in this case, we need to use color=always.

Now the 'less' part.  Most versions of less will not correctly interpret the special control characters.  If you run less without -R, you will probably see a lot of added junk in your output.  -R or --RAW-CONTROL-CHARS (the longer name is pretty descriptive in what it does) allows less to interpret the special control characters.

Ok that's it.  Use it and love it.
Post a Comment