I was grep-ing through some RSS feeds today when it struck me that there's got to be a way to highlight the text that grep matches much like the matching text in vi or less is when searching. Well, it turns out there is.
Just like ls, grep supports the --color option. This means with --color=auto, grep will colorize the portion of the line that matches when it sends output to a terminal, but avoid adding the color escape sequences when you're sending the output to a file or pipe. Unlike ls, which relies on some setup to get it displaying colors properly (see: /etc/profile.d/colorls.sh if you don't believe me), setting up grep to colorize matches by default is as easy as defining the environment variable GREP_OPTIONS='--color=auto' in either your local or system-wide shell startup script.
A typical use-case for me is to pipe the output of grep output to less. If you do this too, keep in mind that the right invocation to get colorized output in less is:
grep --color=always foo bar.txt | less -R
The -R argument to less allows it to pass ANSI color codes unchanged, and --color=always forces grep to colorize its output even though it is going to a pipe.
If you're interested in customizing the color of the highlighted matches, you can set the GREP_COLOR environment variable. A good source of example colors is available in the adequately-commented /etc/DIR_COLORS that's used for setting up color ls. I like GREP_COLOR='43;30;01' which gives you a nice black on yellow highlight for the matched text.
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment