I find grep
\'s --color=always
flag to be tremendously useful. However, grep only prints lines with matches (unless you ask for context lines). Give
The -z
option for grep is also pretty slick!
cat file1 | grep -z "pattern"
It might seem like a dirty hack.
grep "^\|highlight1\|highlight2\|highlight3" filename
Which means - match the beginning of the line(^) or highlight1 or highlight2 or highlight3. As a result, you will get highlighted all highlight* pattern matches, even in the same line.
To highlight patterns while viewing the whole file, h can do this.
Plus it uses different colors for different patterns.
cat FILE | h 'PAT1' 'PAT2' ...
You can also pipe the output of h
to less -R
for better reading.
To grep and use 1 color for each pattern, cxpgrep could be a good fit.
Alternatively you can use The Silver Searcher and do
ag <search> --passthrough
You can also create an alias. Add this function in your .bashrc (or .bash_profile on osx)
function grepe {
grep --color -E "$1|$" $2
}
You can now use the alias like this: "ifconfig | grepe inet
" or "grepe css index.html
".
(PS: don't forget to source ~/.bashrc
to reload bashrc on current session)
Here is a shell script that uses Awk's gsub function to replace the text you're searching for with the proper escape sequence to display it in bright red:
#! /bin/bash
awk -vstr=$1 'BEGIN{repltext=sprintf("%c[1;31;40m&%c[0m", 0x1B,0x1B);}{gsub(str,repltext); print}' $2
Use it like so:
$ ./cgrep pattern [file]
Unfortunately, it doesn't have all the functionality of grep.
For more information , you can refer to an article "So You Like Color" in Linux Journal