bash 彩色文本和管道
我有一个 Perl 脚本,可以在 bash 下输出一些彩色文本。例如,这将输出一个红色字符串:
perl -e 'print "\e[1;31m RED \e[m"
当我通过管道将其传输到另一个程序时,例如 vim ... | vim -
,我可以看到颜色格式化杂乱字符:
^[[1;31m RED ^[[m
并且我希望跳过它们。例如,对于grep
,您会在 bash 中看到颜色,但当输出重定向时它们会被跳过。
怎么做呢?
I have a Perl script that outputs some colored text under bash. For example, this will output a red string:
perl -e 'print "\e[1;31m RED \e[m"
When I pipe it to another program, e.g. vim ... | vim -
, I can see the color formating clutter-characters:
^[[1;31m RED ^[[m
and I want them to be skipped. It happens for example for grep
, that you see colors in bash, but they are skipped when the output is redirected.
How to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 Term::ANSIColor 生成转义序列,您可以设置
ANSI_COLORS_DISABLED
环境变量以禁用转义序列生成)。您可以使用
-t
文件测试来查明输出是否到 tty(或 检测您的脚本是否正在交互运行)。然后,在输出任何序列之前在 Perl 脚本中设置环境变量。
比如:
应该这样做。
If you use Term::ANSIColor for generating the escape sequences, you can set the
ANSI_COLORS_DISABLED
environment variable to disable escape sequence generation).You can use the
-t
file test to find out if the output is to a tty (or detect if your script is being run interactively).Then, set the environment variable in the Perl script before any sequences are output.
Something like:
should do it.
您必须找出 stdout 是什么类型的句柄。我不记得细节了,但可以找出句柄是否指向文件、伪 tty(终端窗口)或管道。
You have to find out what kind of handle stdout is. I don't remember the details but it is possible to find out whether a handle points to a file, a pseudo tty (terminal window), or a pipe.
对于 grep,grep 检测到其输出不会发送到终端,并且不会创建转义序列。
另一种方法是使用
sed
去除这些转义序列:(注意:还有更多 ANSI 转义序列 比这更好;但这应该覆盖颜色。)
For grep, grep detects that its output is not going to the terminal and does not create the escape sequences.
Another approach would be to use
sed
to strip out those escape sequences:(NOTE: There are a lot more ANSI escape sequences than this; but this should cover the colors.)