【问题标题】:awk output using printf and color使用 printf 和颜色的 awk 输出
【发布时间】:2019-12-24 22:42:49
【问题描述】:

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

目前我正在使用

off='\033[0m'   
gry='\033[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", $1,coll,$3,$4)}' coll="${colored}"

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

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

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

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

我想要(带有颜色的第二列)

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

【问题讨论】:

  • 请将该示例输入的所需输出(无描述)添加到您的问题(无评论)。
  • 只增加第二个字段的宽度说明符。使用 20 对我来说似乎相当不错。这些在终端上可能是零宽度,但 AWK 会计算它们。
  • 更新示例
  • \[\] 代码特定于 Bash,并且仅在 Bash 提示符中真正有用。

标签: bash awk terminal solaris


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2022-08-06
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多