在awk中的环境变量中引用ANSI转义序列

时间:2022-05-26 19:34:22

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.

我正在共享一个源文件,为不同的颜色定义不同的ANSI转义码。代码源自一个shellcript(bash),它也启动一个awk脚本,并在awk中引用envvars。

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

但是我没有得到我想要的输出 - 即颜色。

Examples in bash:

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):

awk中的示例(envvars仍然导出/设置):

  # 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.

我假设答案就在我面前,但我现在还没找到。

2 个解决方案

#1


1  

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:

有一种方法可以实现这一点,但您需要稍微区别地声明颜色转义序列。使用ANSI C引用直接插入转义序列,而不是使用转义引导的字符串,并让shell稍后展开:

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).

这应该按预期工作。我也相信这是声明颜色的最佳方式(例如,它在Zsh的colors contrib函数中以这种方式完成)。

#2


1  

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

请尝试使用以下awk命令(稍微修改一下):

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

#1


1  

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:

有一种方法可以实现这一点,但您需要稍微区别地声明颜色转义序列。使用ANSI C引用直接插入转义序列,而不是使用转义引导的字符串,并让shell稍后展开:

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).

这应该按预期工作。我也相信这是声明颜色的最佳方式(例如,它在Zsh的colors contrib函数中以这种方式完成)。

#2


1  

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

请尝试使用以下awk命令(稍微修改一下):

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