Reputation: 99
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?
Upvotes: 1
Views: 1966
Reputation: 22803
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 }"
Upvotes: 3