sastorsl
sastorsl

Reputation: 2135

Referencing ANSI escape sequences in environment variables within awk

I'm sharing a source file defining different ANSI escape codes for different colors. The codes are sourced in a shellscript (bash) which also starts an awk script and the envvars are referenced in awk.

However I'm not getting the output I want - i.e., the colors.

Examples in bash:

export Red='\033[0;31m'
export Color_Off='\033[0m'

  # This works, Output is "Hello" in Red
echo $Red Hello $Color_Off

Examples in awk (the envvars are still exported/set):

  # This does not
$ awk 'BEGIN { print "Output: " ENVIRON["Red"] "Hello" ENVIRON["Color_Off"] }'
Output: \033[0;31mHello\033[0m

  # This works, Output is "Hello" in Red
awk 'BEGIN { R="\033[0;31m" ; O="\033[0m" ; print R "Hello" O }'

I'm assuming the answer is lying there right in front of me, but I fail to find it just now.

Upvotes: 1

Views: 859

Answers (2)

4ae1e1
4ae1e1

Reputation: 7634

There is a way to achieve this, but you need to declare color escape sequences slightly differently. Use ANSI C quoting to directly insert escape sequences instead of using a escape-led string and letting the shell expand later:

export Red=$'\e[0;31m'
export Color_Off=$'\e[0m'
awk 'BEGIN { print "Output: " ENVIRON["Red"] "Hello" ENVIRON["Color_Off"] " Bye" }'

This should work as expected. I also believe this is the superior way to declare colors (for instance, it's done this way in Zsh's colors contrib function).

Upvotes: 1

Tom Durand
Tom Durand

Reputation: 21

Try the following awk command instead (slightly modified from yours):

$ awk -v R=$Red -v O=$Color_Off 'BEGIN { print R "Hello" O }'

Upvotes: 1

Related Questions