突出显示echo中的变量

时间:2012-06-28 16:28:28

标签: bash colors

鉴于以下内容:

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

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

1 个答案:

答案 0 :(得分: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