Add colours to output of existing CLI commands

I would like to create a function / alias that colorizes the output of another command. Is there a best-practice way to do so?

For instance, let's take the alias command, whose output looks something like this:

Original

In the standard bash/zsh, this is all in the same colour. However, I'd like to adjust the output so that the part before the alias itself (the part before the =) is green, and the aliased command (the part after =) is red, for instance.

Obviously, alias is just an example, as I would like to add colours to other commands.

My current solution uses awk:

alias | awk -F"=" '{print "\033[1;32m" $1 "\033[0m=\033[1;31m"$2"\033[0m "}'

MWE

I don't find it particularly appealing (especially the colour codes). It also appears that this approach will become much more complicated for more complex commands (e.g. add colour output to top or ps) and also does not seem very maintainable in the long run.

Any ideas on how to make this better / easier ?

PS: I guess this is a Unix/Linux terminal question in general, but since I work primarily on OS X, I decided to start asking here...


EDIT: I now found this answer, that proposes using functions to make awk output look prettier. I'm not sure though if I want to have lots of formatting functions ghosting around my terminal. Still hoping for something cleaner...

Here's their example:

function red(s) {
    printf "\033[1;31m" s "\033[0m "
}

function green(s) {
    printf "\033[1;32m" s "\033[0m "
}

{
    print red($1), green($2), blue($3)
}

Solution 1:

Especially since you're already using zsh, I would recommend using the existing highlighter framework (and builtin highlighters) of zsh-syntax-highlighting or fast-syntax-highlighting Based on a preliminary review, both should have sufficient documentation to hopefully allow you to set up your preferred environment.

Here's a screenshot of zsh-syntax-highlighting's default parser operating on the parsing command you provided (meta, right?)

enter image description here