Shell – How to add a prefix to input I receive from a pipe via awk and color the prefix conditionally

awkcolorsshell-script

Is there a way to add a prefix to lines received (and filtered) via awk – yes I know that's possible so far – and then conditionally (e.g. based on the existence of the $PS1 variable of the surrounding Bash script or [ -t 1 ]) color it using ANSI escape sequences?

I know how to add a prefix using the ^ anchor and about two or three other ways and I know how to use escape sequences in Bash echo and printf.

How – if at all – can I color the output produced by awk as outlined, based on a condition that can be evaluated inside an inline awk script?

NB: I have mawk or gawk at my disposal, mawk is default.

Best Answer

if [ -t 1 ]; then
  eval "$(printf 'COLOR_ON="\033[31m" COLOR_OFF="\033[m"')"
else
  COLOR_ON= COLOR_OFF=
fi
export COLOR_ON COLOR_OFF
awk '{print ENVIRON["COLOR_ON"] "prefix: " ENVIRON["COLOR_OFF"] $0}'

Or:

[ ! -t 1 ]
awk -v color="$?" '{
   print((color ? "\033[31m" : "") "prefix: " (color ? "\033[m" : "") $0)}'
Related Question