Q:

How to color format output from awk

so I am printing out (echo), 7 variables (strings) with different lengths, and passing it to awk to printf them nicely aligned. Each field has a different field length set.
Example:
$ echo "one MISSING three four five six seven" | awk '{printf "%-17s %-29s %-22s %-25s %-12s %-11s %-25s\n", $1, $2, $3, $4, $5, $6, $7}'
one               MISSING                       three                  four                      five         six         seven                    

But .. there are instances when the script that generates these variables don't have a real value, so I populate them with the string "MISSING".
I would like awk to print the string MISSING in red .. this string could be on any field.
I did this:
echo "one MISSING three four five six seven" | awk '{gsub(/MISSING/,"\033[0;31m&\033[0m\t");printf "%-17s %-29s %-22s %-25s %-12s %-11s %-25s\n", $1, $2, $3, $4, $5, $6, $7}'
one               MISSING            three                  four                      five         six         seven                    

and it does print nicely in red the word MISSING, but it messes up with the output, the fields are not aligned anymore. So when more records are read (for loop) the output is not aligned anymore. As the word MISSING may be on any field.
Something is going on with the printf formatting that it doesn't respect the length for that specific field, it makes it much smaller.
Thank you!

A:

An alternative solution is to insert the color control codes after the formatting:
echo "one MISSING three four five six seven" |
awk '{s = sprintf("%-17s %-29s %-22s %-25s %-12s %-11s %-25s", $1, $2, $3, $4, $5, $6, $7)
      gsub(/MISSING/, "\033[0;31m&\033[0m", s)
      print s}'

