【问题标题】:Highlight variables in echo在 echo 中突出显示变量
【发布时间】:2012-06-28 16:28:27
【问题描述】:

鉴于以下情况:

text="The quick $color fox jumps over the $adjective dog"

如何回显$text,$color 和 $adjective 值在 bash 中着色,但不更改变量?

例子:

$ echo -e --highlight-variables $text
The quick \e[00;31mbrown\e[00m fox jumps over the \e[00;31mlazy\e[00m dog

(实际颜色除外)

然后:

$ echo -e $text
The quick brown fox jumps over the lazy dog

不会有颜色变化。

我希望能够使用less 输出文本,以便用户可以在控制台中查看它,然后将变量写入文件,但文件中不应包含颜色信息。我正在执行的实际代码如下所示:

echo -e $text | less
echo "Is this acceptable?"
read accept
if [ "$accept" == "y" ]
  then
  echo -e $text > output.txt
fi

如果我用颜色包装变量,转义的文本会被放入文件中。

【问题讨论】:

  • 你不能完全那样做。没有办法知道扩展发生在哪里。您必须使用一个数组并将转义码(应该从 tput 生成)和文本拼凑在一起。

标签: bash colors


【解决方案1】:

您只需要在打印之前删除 ansi 序列。

nocolor()
{
perl -pe "s/\e\[\d+(?>(;\d+)*)m//g;"
}

echo -e $text | less
echo "Is this acceptable?"
read accept
if [ "$accept" == "y" ]
  then
  echo -e $text | nocolor > output.txt
fi

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-04
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2015-07-28
    • 2019-07-03
    相关资源
    最近更新 更多