在Unix中删除ANSI颜色转义的最佳方法

时间:2011-09-12 22:44:20

标签: perl unix

我有一个perl progaram,它的打印输出颜色。如果我重新扫描文件中的输出并在vi中打开它,我会看到颜色特殊字符。 像这样的东西。

^[[31;43mAnd this is red on_yellow too^[[0m

从输出文件中删除此颜色字符的最佳方法是什么?

由于

更新

我尝试了正则表达式。它对我有用:

 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

2 个答案:

答案 0 :(得分:11)

Perl模块Term::ANSIColor提供了一个函数colorstrip()来完成这项工作。例如,

ls --color | perl -MTerm::ANSIColor=colorstrip -ne 'print colorstrip($_)'

模块Term::ANSIColor是Perl核心的一部分。

答案 1 :(得分:9)

巧合的是我只需要解决这个问题,这就是我提出的正则表达式:

while (<>) {
    s/\e\[[\d;]*[a-zA-Z]//g;
    print;
}

我只是通过检查一些示例输出(特别是grep --color=always ...的输出)来得出这个,所以它可能无法覆盖你期望的所有转义。

根据this site上的信息,最后一个字符类可能会从[a-zA-Z]缩短为[mK]