Colour highlighting output based on regex in shell

There is an answer in superuser.com:

your-command | grep -E --color 'pattern|$'

or

your-command | grep --color 'pattern\|$'

This will "match your pattern or the end-of-line on each line. Only the pattern is highlighted..."


You could try (maybe needs a bit more escaping):

BLUE="$(tput setaf 4)"
BLACK="$(tput sgr0)"
command | sed "s/^ERROR /${BLUE}ERROR ${BLACK}/g"

If you want to enable this globally, you'll want a terminal feature, not a process that you pipe output into, because a pipe would be disruptive to some command (two problems are that stdout and stderr would appear out-of-order and buffered, and that some commands just behave differently when outputting to a terminal).

I don't know of any “conventional” terminal with this feature. It's easily done in Emacs, in a term buffer: configure font-lock-keywords for term-mode.

However, you should think carefully whether you really want that feature all the time. What if the command has its own colors (e.g. grep --color, ls --color)? Maybe it would be better to define a short alias to a colorizer command and run myCommand 2>&1|c when you want to colorize myCommand's output. You could also alias some specific always-colorize commands.

Note that the return status of a pipeline is its last command, so if you run myCommand | c, you'll get the status of c, not myCommand. Here's a bash wrapper that avoids this problem, which you can use as w myCommand:

w () {
  "$@" | c
  return $PIPESTATUS[0]
}

You can use programs such as:

  • spc (Supercat)
  • grc (Generic Colouriser)
  • highlight
  • histring
  • pygmentize
  • grep --color

You can do something like this, but the commands won't see a tty (some will refuse to run or behave differently or do weird things):

exec > >(histring -fEi error)    # Bash

Tags:

Linux

Shell

Bash