本文介绍了通过bash在tput结果上使用column命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量"x",它包含两列和两行.我想以红色打印"hi",所以我使用了 tput ,结果将结果打印为红色.但是我还需要以正确的对齐方式打印列,因为我使用了 column -t ,但是这会使输出失真.这是由于通过tput添加了一些控制字符的事实.

I have a variable "x" , which contains two columns and two row. I wanted to print "hi" in RED color, so I took help of tput ,which printed the result in red. But I also needed to print the columns in proper alignment for that I used column -t but it is distorting the output. This was due to the fact that some control chars are added by 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"打印为红色.

Tried to debug ,found that tput is adding some control chars to make "hi" print in red.

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

问题:

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

How to "column -t" on colored output from tput?

@Diego Torres Milano的结果(全部为红色)

Result(ALL IN RED) from @Diego Torres Milano

hello  31mhi  Bm  whatsup
hey    howdy   cya

推荐答案

您可以使用一种简化的标记,在这种情况下,您的红色(使用 vim 输入它的类型 + + )

You can use a kind of simplified markup, in this case ^A for your red (to enter it using vim type + +)

y="hello ^Ahi whatsup
hey howdy ya"

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

并且输出符合预期(hi为红色):

and the output is as expected (hi is in red):

hello  hi     whatsup
hey    howdy  ya

编辑

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

EDIT

if your column counts the control chars, then use any char that's not appearing in your values and then replace them, like

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

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

产生

这篇关于通过bash在tput结果上使用column命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 18:35