Redirect/Pipe output and set environment variable

2

Basically, I have a file whose lines I want to color with different colors if it matches 1 of 2 regular expressions with grep. If regexp1 is matched, then use one color; if regexp2 is matched, use another.

However, grep colors with one color at a time, so what I'd like to do is pipe the output of grep into another grep statement witch a different color.

However, grep color is controlled with an environment variable GREP_COLOR (this is deprecated in favour of GREP_COLORS, but didn't get that working on windows so I'm using GREP_COLOR instead)

So the batch file will look something like this:

@echo off
setlocal
set GREP_COLOR=06;32
echo GREEN RED OTHER | grep --color=always --line-buffered "GREEN" | grep --color=always -E "RED"
endlocal

How can I change GREP_COLOR for the second grep call?

I have it working with 2 batch files, but there's got to be a way to do this with a single batch file:

ctest1.bat:

@echo off
setlocal
set GREP_COLOR=06;32
echo GREEN RED OTHER | grep --color=always --line-buffered "GREEN" | ctest2.bat
endlocal

ctest2.bat:

@echo off
setlocal
set GREP_COLOR=01;31
grep --color=always -E "RED" 
endlocal

Any ideas? Seems like it should be simple but I wasted good 2 hours trying to make it into 1 batch file without any success.

Rado

Posted 2011-05-03T00:06:39.287

Reputation: 509

Answers

0

Seems like a temp file solution should work.

Something like:

@echo off
setlocal
set GREP_COLOR=06;32
echo GREEN RED OTHER | grep --color=always "GREEN" > %temp%\color.tmp
set GREP_COLOR=01;31
grep --color=always "RED" %temp%\color.tmp
del %temp%\color.tmp
endlocal

I generally dislike creating temp files, but it's the quick solution that comes to mind.

Jason Sherman

Posted 2011-05-03T00:06:39.287

Reputation: 1 071

Temp file does not work for me because I will be coloring input that is dynamic - output from a build that runs for hours and continuously outputs data. The echo GREEN RED OTHER is just an example. The way the batch file will be normally used would be: gmake ... | color.bat. I already have a solution as described in the question above that will let me do gmake ... | color1.bat | color2.bat, but I think there is a way to do it only with one file. Something like grep | (set GREP_COLOR=x & grep) – Rado – 2011-05-03T03:41:49.510