glendeni has asked for the wisdom of the Perl Monks concerning the following question:

I output some text to a terminal by inserting colors via strings ala my $red = "\033[31m"; I would like to sometimes remove that markup for printing to a normal file. But all of the following fail to remove the markup:

( my $nocolorsline = $line ) =~ s/\033\[[\d;]*[a-zA-Z]//g; ( my $nocolorsline = $line ) =~ s/\e\[[\d;]*[a-zA-Z]//g; ( my $nocolorsline = $line ) =~ s/\Z\[\d;]*[a-zA-Z]//g; ( my $nocolorsline = $line ) =~ s/\x1b\[[\d;]*[a-zA-Z]//g;
What am I missing ?
Jack
LATER - I was missing that I was changing the wrong line :-( So the above do work. Sorry for the inconvenience. Can't see how to delete this post.

Replies are listed 'Best First'.
Re: Can't remove ANSI markup
by Corion (Patriarch) on Oct 17, 2019 at 08:14 UTC

    I would go the other way around and define the colors as global variables and set these to be empty in the case where no colors are wanted:

    my $red = "\033[31m"; # is there a semicolon missing at the end of the + ANSI escape? if( $ENV{NO_COLOR} || ! -t) { $red = ""; }

    See also https://no-color.org and Term::ANSIColor::Conditional.

Re: Can't remove ANSI markup
by 1nickt (Canon) on Oct 17, 2019 at 02:09 UTC

    Hi, there should be a better way, maybe colorstrip() from Term::ANSIColor ?

    Or, perhaps this will help:

    $ perl -Mstrict -wE 'my $str = q{[\033[96m]word[\033[0m]}; say $str; s +ay $str =~ s/ \[ \\? \d+ [a-zA-Z]? \]? //gxr' [\033[96m]word[\033[0m] word
    ( note: barely tested and likely to be fragile)


    The way forward always starts with a minimal test.