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.
\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. So line will be treated immediately.
So I will hear some beep when I connect or disconnect ethernet cable.
Of course, instead of link up
pattern, you could watch for USB
in same file, or even search for from=
in some /var/log/mail.log
...
sed
. thesed
solution gets you multiple colors at the cost of added complexity (instead of about 30 characters you have about 60 characters).sed
you could event send a beep on console terminal: stackoverflow.com/a/69266748/1765658