I have been working on a simple shell script to highlight text in the terminal for the last hour. At first, I looked at it from the wrong angle, but after a short break, I finally realized the simplest possible solution.
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 a short break, I came with two simple solutions:
sed
using additional code replacementssuper sed stream editor
using a negative look-behind assertion
Shell script
#!/bin/sh 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"); else 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"); fi done else while read line; do echo $line; done fi
Examples
Highlight words in capital letters.
Highlight numbers, shell, root, or daemon username.
Highlight the date and time for each log entry.
Please be aware that the above-mentioned examples use ssed
command internally.