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:

#!/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.

Interested in doing anything to your PDFs beyond reading and annotating?Use sodapdf editor to make updates such as adjusting content, layout, margins, and more.

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

5 thoughts on “Highlight text on the fly thanks to terminfo and sed.”

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

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.