1

我有一个变量 "x" ,它包含两列和两行。我想用红色打印“hi”,所以我求助了tput,它用红色打印了结果。但是我还需要以正确对齐的方式打印我使用的列,column -t但这会扭曲输出。这是因为 tput 添加了一些控制字符。

x="hello $(tput setaf 1)hi $(tput sgr0) whatsup
hey howdy cya"


echo "$x"
hello hi  whatsup
hey howdy cya

echo "$x"|column -t
hello  hi              whatsup
hey    howdy  cya

我期待:

hello  hi     whatsup
hey    howdy  cya

尝试调试,发现tput正在添加一些控制字符以使“hi”打印为红色。

echo "$x"|cat -A
hello ^[[31mhi ^[(B^[[m whatsup$
hey howdy cya$

问题:

如何“ column -t”在 tput 的彩色输出上?

编辑:来自@Diego Torres Milano 的结果(ALL IN RED)

hello  31mhi  Bm  whatsup
hey    howdy   cya
4

1 回答 1

0

您可以使用一种简化的标记,在这种情况下^A为您的红色(使用vimtype CTRL+ v CTRL+输入a

y="hello ^Ahi whatsup
hey howdy ya"

echo "$y"|column -t|sed -E "s@^A([[:alnum:]]+)@$(tput setaf 1)\1$(tput sgr0)@g"

并且输出与预期一致(hi 为红色):

hello  hi     whatsup
hey    howdy  ya

编辑

如果您column计算控制字符,则使用任何未出现在您的值中的字符,然后替换它们,例如

y="|hello !hi |whatsup
|hey |howdy |ya"

echo "$y"|column -t|sed -E "s@\\|@@g; s@!([[:alnum:]]+)@$(tput setaf 1)\1$(tput sgr0)@g;"

产生

列颜色

于 2018-12-14T07:03:52.197 回答