使用 printf 和颜色的 awk 输出

awk output using printf and color

我正在旧版本的 Solaris 上编写脚本。列不存在。我想为字符串的第二列着色并将其格式化为基本列。

目前我正在使用

off='3[0m'   
gry='3[1;90m'
line="test1 test2 test3 test4"
colored=$(echo -e "${gry}1.23${off}")
echo -e "${line}" | awk -F" " '{printf("%-10s%-10s%-10s%s\n", ,coll,,)}' coll="${colored}"

但是当 运行 时,第二个彩色列将把第 3 个列压在上面。 没有颜色代码,格式很好。

我认为这可能与零长度字符有关

off='\[3[0m\]' 
gry='\[3[1;90m\]'

但这只会打印额外的括号。

我想要(第 2 列有颜色)

test1     1.23     test3          test4
test1     1.23     test3          test4
test1     1.23     test3          test4

但得到

test1     1.23test3          test4
test1     1.23test3          test4
test1     1.23test3          test4

printf 的格式接收您的 ANSI CSI 代码并将它们计入字符串参数宽度,无论它们是否实际打印。

因为您 总是 为第二列着色,您可以像这样在 printf 的格式字符串中移动 ANSI CSI 序列:

line="test1 test2 test3 test4"
colored="1.23"
echo -e "${line}" | awk -F" " '{printf("%-10s3[1;90m%-10s3[1;0m%-10s%s\n", ,coll,,)}' coll="${colored}"