如何根据条件为awk的输出着色

How to color the output of awk depending on a condition

我有一个输入文件 test.txt 包含以下内容:

 a 1 34
 f 2 1
 t 3 16
 g 4 11
 j 5 16

我使用 awk 只打印字符串 2 和 3:

awk '{print  " " }' test.txt

有没有办法根据条件只为输出的第二个字符串着色,如果值高于 15,则打印为橙色,如果值高于 20,则打印为红色。它会给出相同但有颜色的:

1 34(red)
2 1
3 16(orange)
4 11
5 16(orange)

输入可以包含更多行,顺序不同。

您可以执行以下操作:

awk '{printf "%s ", }
      > 15 {printf "3[33m"}
      > 20 {printf "3[31m"}
     {printf "%s3[0m\n", }' test.txt

很遗憾,我不知道橙色 ansi 转义码...

另一种方法:

awk -v color1="3[33m" -v color2="3[31m" -v reset="3[0m" '
      > 15 &&  <= 20 {=color1  reset}
      > 20 {=color2  reset}
     {print , }' test.txt

这个 awk 命令应该做你想做的事:

awk -v red="$(tput setaf 1)" -v yellow="$(tput setaf 3)" -v reset="$(tput sgr0)" '{printf "%s"OFS"%s%s%s\n", , (>20)?red:(>15?yellow:""), , reset}'

这里的关键位是

  • 使用 tput 来正确表示当前终端的颜色设置(而不是硬编码特定的转义序列)
  • 使用 -v 设置 awk 命令用来构造其输出的变量值

上面的脚本写得很简洁,但可以这样写得不那么简洁:

{
    printf "%s"OFS, 
    if ( > 20) {
        printf "%s", red
    } else if ( > 15) {
        printf "%s", yellow
    }
    printf "%s%s\n", , reset
}

编辑:Ed Morton 正确地指出,上面的 awk 程序可以通过使用 color 变量并将颜色选择与打印分开来简化。像这样:

awk -v red="$(tput setaf 1)" -v yellow="$(tput setaf 3)" -v reset="$(tput sgr0)" \
'{
    if (>20) color=red; else if (>15) color=yellow; else color=""
    printf "%s %s%s%s\n", , color, , reset
}'
awk '{if(>15 && <=20){="3[1;33m"  "3[0m"};if(>20){="3[1;31m"  "3[0m"};print}' file

细分

(>15 && <=20){="3[1;33m"  "3[0m"}  # if field 2>15 and =<20, then add colour code to field 2.

if(>20){="3[1;31m"  "3[0m"} ## if field 2>20, then add colour code to field 2.

print #print line afterwards