I’m trying to write a perl script which takes the output of colorgcc (or any other script that prints colored text to terminal), adds/removes parts of the string, and then prints the result in the same color as the input string.
The following code will print “Hello World” in front of each line produced by the color_producing_script. The output will be all black, while the input is multicolored. How can I modified this script to conserve the original colors?
open(CMD, "color_producing_script |");
while(<CMD>) {
print 'Hello World' . $_;
}
I’m using bash terminal.
Edit
Per the excellent first comment, this is not a Perl issue per se. Just running color_producing_script | cat strips the color off. So the question can be rephrased to “How do you force color through the pipe?”
Edit 2
It looks like the latest version of gcc (1.3.2) includes the CGCC_FORCE_COLOR environment variable in the if clause, and if it’s defined, colorgcc forces color:
export CGCC_FORCE_COLOR=true
Does
color_producing_scriptchange its behavior when it’s used in a pipe? Tryat the command line. It may have an option to force color output even when it is.
The Perl script,
colorgcc, is specifically checking to see if output is to a non-tty and skipping the colorization if that’s the case.Edit:
You could modify the script in one or more of the following ways:
~/.colorgccrcconfiguration fileYou could also use the
expectscriptunbufferto create a pseudo-tty like this:(where
catis a standin recipient).All of this is based on using
colorgccfrom the command line. There should be analogs for doing similar things within a Perl script.