20

This file has 3 fields. I wanted e.g. the first 2 fields in green, and the third in white (NB : black background), so I tried :

awk '{print "\033[0;32m"$1"\033[0m", "\033[0;32m"$2"\033[0m", "\033[0;37m"$3"\033[0m"} }' chrono.txt

and everything was green…

How must I proceed (if it is possible) ?

ThG
  • 2,361
  • 4
  • 22
  • 33

2 Answers2

35

To get color output from awk, you can use this approach.

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

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

function blue(s) {
    printf "\033[1;34m" s "\033[0m "
}

{
    print red($1), green($2), blue($3)
}
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
  • 10
    Be careful with these functions. They are using an external string as the format specifier. If the string contains format characters (%, etc.), it will fail. Better use something like `function red(string) { printf ("%s%s%s", "\033[1;31m", string, "\033[0m "); }` – Juan Calero Sep 04 '12 at 09:47
  • I couldn't get the answer to work, nor even this suggestion. But the following worked for me: `function yellow(s) {return "\033[1;93m" s "\033[1;39m"}` – Tim Apr 20 '20 at 13:06
10

An alternative to using awk functions is passing the colors in shell variables. E.g.

RED='\033[01;31m'
GREEN='\033[01;32m'
YELLOW='\033[01;33m'
BLUE='\033[01;34m'
NONE='\033[0m'

echo "Col1 Col2 Col3 Col4" | \
awk -v r=$RED -v y=$YELLOW -v g=$GREEN -v b=$BLUE -v n=$NONE \
 '{printf r$1n y$2n g$3n b$4n "\n"}'
Matt Muggeridge
  • 465
  • 3
  • 11