【问题标题】:Using column command on tput result over bash通过 bash 对 tput 结果使用列命令
【发布时间】:2018-12-15 08:48:13
【问题描述】:

我有一个变量 "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$

问题:

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

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

hello  31mhi  Bm  whatsup
hey    howdy   cya

【问题讨论】:

    标签: bash tput


    【解决方案1】:

    您可以使用一种简化的标记,在这种情况下,^A 代表您的红色(要使用 vim 输入它,请输入 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;"
    

    产生

    【讨论】:

    • 您好,在答案中添加了输出。谢谢。它和你的不一样。
    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 2019-09-09
    • 2017-10-13
    • 2014-04-07
    • 2020-12-09
    • 1970-01-01
    • 2020-02-02
    相关资源
    最近更新 更多