简体   繁体   中英

Using column command on tput result over bash

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

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

列颜色

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM