在 Unix 中删除 ANSI 颜色转义的最佳方法 [英] Best way to remove ANSI color escapes in Unix
问题描述
我有一个 perl 程序,它的打印输出带有颜色.如果我重定向文件中的输出并在 vi 中打开它,我会看到颜色特殊字符.像这样的东西.
^[[31;43m而且这个也是红色 on_yellow ^[[0m
从输出文件中删除此颜色字符的最佳方法是什么?
谢谢
更新:
我试过这个正则表达式.它对我有用:
cat -v a|head^[[30;41m这是黑色的_红色^[[0m^[[30;41m这也是黑色的_红色^[[0m^[[30;42m 这是黑色 on_green^[[0m^[[30;42m这也是黑色 on_green ^[[0m^[[30;43m这是黑色 on_yellow^[[0m^[[30;43m这也是黑色的_黄色的^[[0m^[[30;44m 这是黑色 on_blue^[[0m^[[30;44m这也是黑色 on_blue ^[[0m^[[30;45m 这是黑色 on_magenta^[[0m^[[30;45m这也是黑色的_洋红色^[[0m$ cat -v a|head|perl -lane 's/\^\[\[\d+(;\d+)*m//g;打印'这是黑色 on_red这也是黑色 on_red这是黑色 on_green这也是黑色 on_green这是黑色 on_yellow这也是黑色 on_yellow这是黑色 on_blue这也是黑色 on_blue这是黑色 on_magenta这也是黑色 on_magenta
碰巧我刚好解决了这个问题,这就是我想出的正则表达式:
while (<>) {s/\e\[[\d;]*[a-zA-Z]//g;打印;}
我只是通过检查一些示例输出(特别是 grep --color=always ...
的输出)得出的,因此它可能无法涵盖您期望的所有转义.>
根据本站信息,最后一个字符类可能会从 [a-zA-Z]
缩短为 [mK]
.
I have a perl progaram its prints output with color. if I rediect the output in the file and open it in vi I see color special character. something like this.
^[[31;43mAnd this is red on_yellow too^[[0m
What is the best way to remove this color character from the output file?
Thanks
Update:
I tried thid regex. it works for me:
cat -v a|head
^[[30;41mThis is black on_red^[[0m
^[[30;41mAnd this is black on_red too^[[0m
^[[30;42mThis is black on_green^[[0m
^[[30;42mAnd this is black on_green too^[[0m
^[[30;43mThis is black on_yellow^[[0m
^[[30;43mAnd this is black on_yellow too^[[0m
^[[30;44mThis is black on_blue^[[0m
^[[30;44mAnd this is black on_blue too^[[0m
^[[30;45mThis is black on_magenta^[[0m
^[[30;45mAnd this is black on_magenta too^[[0m
$ cat -v a|head|perl -lane 's/\^\[\[\d+(;\d+)*m//g; print'
This is black on_red
And this is black on_red too
This is black on_green
And this is black on_green too
This is black on_yellow
And this is black on_yellow too
This is black on_blue
And this is black on_blue too
This is black on_magenta
And this is black on_magenta too
Coincidentally I just had to solve this problem, and this is the regexp I came up with:
while (<>) {
s/\e\[[\d;]*[a-zA-Z]//g;
print;
}
I just derived this by examining some example output (in particular, the output of grep --color=always ...
), so it may not cover all the escapes you expect.
According to the information on this site, the last character class could probably be shorten from [a-zA-Z]
to just [mK]
.
这篇关于在 Unix 中删除 ANSI 颜色转义的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!