简体   繁体   English

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

[英]Referencing ANSI escape sequences in environment variables within awk

I'm sharing a source file defining different ANSI escape codes for different colors. 我正在共享一个源文件,为不同的颜色定义了不同的ANSI转义码。 The codes are sourced in a shellscript (bash) which also starts an awk script and the envvars are referenced in awk. 这些代码来自shellscript(bash),该脚本也启动了awk脚本,而envvars在awk中被引用。

However I'm not getting the output I want - ie, 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中的示例(仍然导出/设置envvar):

  # 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. 我以为答案就在我眼前,但是我暂时找不到。

请改用以下awk命令(从您的命令稍作修改):

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

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引号直接插入转义序列,而不是使用以转义为首的字符串,并让外壳稍后扩展:

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 function中以这种方式完成)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM