Highlight text on the fly thanks to terminfo and sed.

A colleague today was looking for a way to pipe something to a command that highlights particular strings of text, keeping intact the stdin, similar to what you can see on some modern distros, ie Gentoo.

Grep is not the way as it only prints the lines which contain the pattern that we are looking for.

While there are a bunch of tools that can do that, like supercat, etc. I felt no need to install additional packages for something you can do with few lines of bash and knowing terminal capabilities.

Therefore I wrote this small script, put it in the PATH env variable. The script uses sed and makes use of the terminfo database and of the terminal capabilities to color the text, here it is in case you find it useful:

1
2
3
4
5
6
7
8
#!/bin/bash
 
red=$(tput bold;tput setaf 1)
normal=$(tput sgr0)
 
while read line; do
  echo $line | sed -e "s/\($1\)/$red\1$normal/"
done

If you don’t like red just read `man tput` and read this link about terminal codes.

Example of usage:

It also accept regexps (in sed syntax, not perl syntax), for example:


$ sudo tail -f /var/log/system.log | highlight [Ss]potify

Comments Posted in Informatica, Lavoro, Linux, Programmazione
Tagged , , , , ,

Comments

  1. pallotron says:

    That is not what was needed Andrei. Grep is excluding lines that don’t match… we need to see the entire file.

  2. Andrei Dumitrescu says:

    Hello Angello,
    ‘grep –color’ does the same thing.

  3. salvo says:

    Ciao Angelo,
    finalmente hai ripreso a scrivere i tuoi post di programmazione.
    Ben tronato e scrivi più frequntemente.

  4. pallotron says:

    Yep, multitail is nice 🙂

  5. Freddy says:

    The following is a must tool worth installing/compiling for any real “log monkey”:

    http://www.vanheusden.com/multitail/