Sed to add color to column for a specific pattern?

Viewed 70

I figured out how to colorize column 3 in green like this:

green=$'\033[1;32m';off=$'\e[m';echo -e "num co1umn1 column2 column3\n=== === === ===\n1 this is me\n2 that is you"|column -t|sed "s/[^[:blank:]]\{1,\}/$green&$off/3";unset green off

CLI result

How do I need to alter my sed command to colorize the pattern 'is' only within column 3 so that the output becomes:

Wanted result

4 Answers

If you want to color the whole word is, you can use (with GNU sed):

sed "s/\bis\b/$green&$off/"
sed "s/\<is\>/$green&$off/"

Here, \b is a word boundary, \< is a leading word boundary and \> is a trailing word boundary.

enter image description here

Else, you can tell sed to start looking for matches from the third line:

sed "3,$ s/[^[:blank:]]\{1,\}/$green&$off/3"

Output:

enter image description here

One way to do this is to ignore the first two lines of the output in sed:

sed "1,2 ! s/[^[:blank:]]\{1,\}/$green&$off/3";

Using sed

$ ... | sed "/^[[:digit:]]/s/\(\([^ ]* \+\)\{2\}\)\([^ ]*\)/\1$green\3$off/"

Modifying the echo to cover a couple other instances of is ...

$ echo -e "num co1umn1 column2 column3\n=== === === ===\n1 is is me\n2 that isn't you" | column -t
num  co1umn1  column2  column3
===  ===      ===      ===
1    is       is       me         # only colorize the 2nd occurrence of "is"
2    that     isn't    you        # don't colorize "isn't" in 3rd column

Extending OP's current sed solution:

sed -r "3,$ s/[^[:blank:]]{1,}/XXX&XXX/3; s/XXXisXXX/${green}is${off}/; s/XXX//g"

Where:

  • 3,$ - apply following sed scripts against line numbers 3-to-EOF (ie, skip 1st 2 lines)
  • first we offset the 3rd column values with XXX bookends (choose a set of characters that you know won't show up anywhere in the data)
  • then colorize XXXisXXX (removing the XXXs at the same time)
  • then remove any remaining XXX (from 3rd column in other rows)

This generates:

enter image description here

Related