简体   繁体   English

在回显中突出显示变量

[英]Highlight variables in echo

Given the following: 给定以下内容:

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

How can I echo $text with $color and $adjective values being colored in bash, but not changing the variable? 如何在bash中用$color$adjective值着色的$text而不显示变量,以回显$text

Example: 例:

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

(except with the actual colors) (实际颜色除外)

But then: 但是之后:

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

would have no color changes. 不会有颜色变化。

I want to be able to output the text with less so the user can review it in the console, but then write the variables to a file, but the file should not have the color info in it. 我希望输出的文字less以便用户可以在控制台中查看它,然后将变量写入文件,但文件中不应包含颜色信息。 The actual code I'm executing looks something like: 我正在执行的实际代码如下所示:

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

If I wrap the variables in color, the escaped text gets put in the file. 如果我将变量用彩色换行,则转义的文本将放入文件中。

You just need to remove ansi sequences before you print. 您只需要在打印前删除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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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