How to highlight text in terminal

I have been working on a simple shell script to highlight text in terminal for the last hour. At first I looked at it from the wrong angle but after short break I finally realized the simplest possible solution which I will describe here for further reference.

At first I tried to use the following sed command but quickly realized that I cannot pipe it multiple times as it will work only for the first time.

sed -e "/\x1b\[1m/,/\x1b0m/! {s/\($highlight\)/\x1b\[1m\1\x1b\[0m/g}"

After short break I came with two simple solutions:

  • sed using additional code replacements
  • super sed stream editor using negative look behind assertion

Shell script


if [ ! -z "$1" ]; then
  while read line; do
    if [ -n "$(which ssed)" ]; then
      echo $(echo "$line" | ssed -R -e "s/(?<!\x1b\[|\x1b\[[01])($1)/\x1b\[1m\1\x1b\[0m/g");
      echo $(echo "$line" | sed -e "s/\x1b\[1m/\x11/g" -e "s/\x1b\[0m/\x12/g" -e "s/\($1\)/\x1b\[1m\1\x1b\[0m/g" -e "s/\x11/\x1b\[1m/g"  -e "s/\x12/\x1b\[0m/g");
  while read line; do echo $line; done


Highlight words in capital letters.

Highlight numbers, shell, root or daemon username.

Highlight date and time for each log entry.

Please be aware that above-mentioned examples use ssed command internally.