Using column command on tput result over bash

孤人 提交于 2019-12-24 10:37:29

问题


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

I was expecting:

hello  hi     whatsup
hey    howdy  cya

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$

Question:

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

EDIT: Result(ALL IN RED) from @Diego Torres Milano

hello  31mhi  Bm  whatsup
hey    howdy   cya

回答1:


You can use a kind of simplified markup, in this case ^A for your red (to enter it using vim type 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"

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;"

which produces



来源:https://stackoverflow.com/questions/53769699/using-column-command-on-tput-result-over-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!