The sed way
As there is already a lot of different solution, but none show sed as solution,
and because sed is lighter and quicker than grep, I prefer to use sed for this kind of job:
sed 's/pattern/\o33[47;31;1m&\o033[0m/' file
This seems less intuitive.
s/pattern/replaced/ is sed replacement command to replace pattern by replaced.
\o33 is the sed syntax to generate the character octal 033 -> Escape.
(Some shells and editors also allow entering <Ctrl>-<V> followed by <Esc>, to type the character directly.)
Esc [ 47 ; 31 ; 1 m is an ANSI escape code: Background grey, foreground red and bold face.
& will re-print the pattern.
Esc [ 0 m returns the colors to default.
You could also highlight the entire line, but mark the pattern as red:
sed -E <file -e \
's/^(.*)(pattern)(.*)/\o33[30;47m\1\o33[31;1m\2\o33[0;30;47m\3\o33[0m/'
Dynamic tail -f, following logfiles
One of advantage of using sed: You could send a alarm beep on console, using bell ascii character 0x7. I often use sed like:
sudo tail -f /var/log/kern.log |
sed -ue 's/[lL]ink .*\([uU]p\|[dD]own\).*/\o33[47;31;1m&\o33[0m\o7/'
-u stand for unbuffered. This ensure that line will be treated immediately.
So I will hear some beep instantly, when I connect or disconnect my ethernet cable.
Of course, instead of link up pattern, you could watch for USB in same file, or even search for from=.*alice@bobserver.org in /var/log/mail.log (If
you're Charlie, anxiously awaiting an email from Alice;)...
Advantage of sed
As sed is a language, you could use many directives, for sample: avoiding imap and pop logs while watching for incoming request on some mail server:
tail -f /var/log/mail.log | sed -ue '
/[[:space:]]\(imap\|pop\)d\[/d;
/[^[:alnum:]]smtpd\[/{
s/.*/\o33[30;47m&\o33[0m/;
s/\(alice\|bob\)@example.com/\o33[31;1m\o7&\o33[30m/;
}
'
This will
- delete lines regarding
imapd or popd servers.
- highlight lines regarding
smtpd server and
- in
smtpd lines highlight and beep when line containing alice@example.com or bob@example.com is found.