1

Working on a shell script (sh, no bash) I'd like to use colors from a variable for column 1 and 3 in awk printf. I want to use a variable in the printf as the script uses color themes, so RED_COLOR may be a different color code than the one I assign here in the example.

I have:

#!/bin/sh
RED_COLOR='\033[0;31m'
GREEN_COLOR='\033[0;92m' 
NO_COLOR='\033[00m'


var1=value1
var2=value2
var3=value3

values="$var1 $var2 $var3"

var1=value4
var2=value5
var3=value6

values="$values
$var1 $var2 $var3"

echo "$values" | awk '{ printf "%-10s %-8s %-8s\n", $1, $2, $3 }'

$values is a list from a for loop, here, I just add them up to represent the data to be presented. The above outputs this list:

value1     value2   value3
value4     value5   value6

I can assign the colors as code, like so for the first column:

echo "$values" | awk '{ printf "\033[0;31m%-10s\033[00m  %-8s %-8s\n", $1, $2, $3 }'

But how can I assign the colors to column 1 and 3, using the variable and not the color code in the printf?

2
  • 1
    Probably you need to switch your quotes around and do some esoteric escaping, like echo "$values" | awk "{ printf \"$color%-10s$color2 %-8s %-8s\\n\", \$1, \$2, \$3 }" Commented Jul 19, 2017 at 7:14
  • That does it, I tinkered with the first part, but not the escaping of the $ fields. Thank you!
    – stargazer
    Commented Jul 19, 2017 at 7:18

1 Answer 1

3

The problem has to do with mixing quotation levels between the shell and the script for awk. If you carefully escape the quotes in the string and the dollars for awk's variables, you can get it to work like this:

echo "$values" | awk "{ printf \"$color%-10s$color2 %-8s %-8s\\n\", \$1, \$2, \$3 }"
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.