When using grep --color=always
I can get pretty color highlighting for regex matches.
However, grep
only returns lines with at least one match.
The simplest solution would be to use egrep --color=always 'text|^'
which would match all line beginnings but only color the desired text.
Here is a script I use to colorize output.
I think I found the idea/snippet on some kind of blog or bash/sed tutorial - can't find it anymore, it was very long time ago.
#!/bin/bash
red=$(tput bold;tput setaf 1)
green=$(tput setaf 2)
yellow=$(tput bold;tput setaf 3)
fawn=$(tput setaf 3)
blue=$(tput bold;tput setaf 4)
purple=$(tput setaf 5)
pink=$(tput bold;tput setaf 5)
cyan=$(tput bold;tput setaf 6)
gray=$(tput setaf 7)
white=$(tput bold;tput setaf 7)
normal=$(tput sgr0)
sep=`echo -e '\001'` # use \001 as a separator instead of '/'
while [ -n "$1" ] ; do
color=${!1}
pattern="$2"
shift 2
rules="$rules;s$sep\($pattern\)$sep$color\1$normal${sep}g"
done
#stdbuf -o0 -i0 sed -u -e "$rules"
sed -u -e "$rules"
Usage:
./colorize.sh color1 pattern1 color2 pattern2 ...
e.g.
dmesg | colorize.sh red '.*Hardware Error.*' red 'CPU[0-9]*: Core temperature above threshold' \
green 'wlan.: authenticated.*' yellow 'wlan.: deauthenticated.*'
Doesn't work well with overlapping patterns, but I've found it very useful anyway.
HTH
This little function works well in my ZShell:
function color_grep {
sed s/$1/$fg[yellow]$1$terminfo[sgr0]/g
}
(Needs
autoload colors zsh/terminfo
)
Maybe you can do something similar?
Edit: Sorry, this won't work with regexes. You will have to tweak it a bit ...
I'm digging this little python utility. If not on debian, use alien to convert to rpm.
http://korpus.juls.savba.sk/~garabik/software/grc.html
regexp=.*red
colours="\033[38;5;160m"
count=once
This is a nice page on terminal colors.
http://www.pixelbeat.org/docs/terminal_colours/
(Queen's english is so colourful.)
You could use the -C<num>
option to grep which shows you <num>
lines of context around your match. Just make sure <num>
is as least as large as the number of lines in your file.
I recently made something similar as a filter. I use it to color the "headers" in a tail with multiple files, like this:
tail -f access.log error.log foo.log | logcol.sh
The headers look like this:
==> access.log <==
I got confused by the quick changes between the different logfiles, so this logcol.sh helps. The ==> is hardcoded for the specific usage but could be a parameter as well.
#!/bin/sh
while read line
do
if test `expr "$line" : "==>.*"` -eq 0 ;
then
printf '\033[0m%s\n' "$line"
else
printf '\033[0;31m%s\n' "$line"
fi
done
Maybe not the most elegant but I think it's quite readable. I hope I don't have any typos ;-) HTH, rob