如何根据条件为awk的输出着色 [英] How to color the output of awk depending on a condition
问题描述
我有一个输入文件test.txt,其中包含以下内容:
I have an input file test.txt containing the fallowing:
a 1 34
f 2 1
t 3 16
g 4 11
j 5 16
我用awk只打印字符串2和3:
I use awk to print only string 2 and 3:
awk '{print $2 " " $3}' test.txt
有没有一种方法可以根据条件仅对输出的第二个字符串着色,如果该值大于15,则以橙色打印;如果该值大于20,则以红色打印.它将给出相同但彩色的:
Is there a way to color only the second string of my output depending on a condition, if the value is higher than 15 then print in orange, if the value is higher than 20, print in red. It will give the same but colored:
1 34(red)
2 1
3 16(orange)
4 11
5 16(orange)
输入内容可能包含更多不同顺序的行.
The input could contain many more lines in a different order.
推荐答案
此awk命令应执行您想要的操作:
This awk command should do what you want:
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}'
这里的关键是
- 使用
tput
来正确表示设置当前终端的颜色(与对特定的转义序列进行硬编码相反) - 使用
-v
设置awk命令用来构造其输出的变量的值
- the use of
tput
to get the correct representation of setting the color for the current terminal (as opposed to hard-coding a specific escape sequence) - the use of
-v
to set the values of the variables the awk command uses to construct its output
上面的脚本写得很简洁,但写得可能不太简洁:
The above script is tersely written but could be written less tersely like this:
{
printf "%s"OFS, $1
if ($3 > 20) {
printf "%s", red
} else if ($3 > 15) {
printf "%s", yellow
}
printf "%s%s\n", $3, reset
}
Ed Morton正确地指出,可以通过使用color
变量并将颜色选择与印刷分开来简化上述awk程序.像这样:
Ed Morton correctly points out that the awk programs above could be simplified by using a color
variable and separating the color choice from the printing. Like this:
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
}'
这篇关于如何根据条件为awk的输出着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!