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

rap*_*y75 1 shell awk

我有一个输入文件test.txt包含fallowing:

 a 1 34
 f 2 1
 t 3 16
 g 4 11
 j 5 16
Run Code Online (Sandbox Code Playgroud)

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

awk '{print $2 " " $3}' test.txt
Run Code Online (Sandbox Code Playgroud)

是否有办法根据条件仅为输出的第二个字符串着色,如果值大于15则以橙色打印,如果值大于20,则以红色打印.它会给出相同但有色的:

1 34(red)
2 1
3 16(orange)
4 11
5 16(orange)
Run Code Online (Sandbox Code Playgroud)

输入可以包含更多不同顺序的行.

Eta*_*ner 9

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

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

这里的关键点是

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

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

{
    printf "%s"OFS, $1
    if ($3 > 20) {
        printf "%s", red
    } else if ($3 > 15) {
        printf "%s", yellow
    }
    printf "%s%s\n", $3, reset
}
Run Code Online (Sandbox Code Playgroud)

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

awk -v red="$(tput setaf 1)" -v yellow="$(tput setaf 3)" -v reset="$(tput sgr0)" \
'{
    if ($3>20) color=red; else if ($3>15) color=yellow; else color=""
    printf "%s %s%s%s\n", $1, color, $3, reset
}'
Run Code Online (Sandbox Code Playgroud)