0

I created a bat file using a Windows port of grep that allows me to search for strings with context search. It looks like this:

grep -C -i "%1" %2 

If I invoke it like this: grep -C -i "Smith" mydoc.doc I get the exact results I am looking for:

Bruce Korn
10 Smith Street 
Durham, NC 

But does anyone know of a way to add the Windows Color command to the bat so that "Smith" will be displayed in green (something like "color 0F" ) added as a pipe or something like that? I just can NOT figure out how to do that (or if it's even possible)

(The grep port does not have coloring or highlighting capability)

Jonathon Reinhart
  • 116,671
  • 27
  • 221
  • 298
Bruce Korn
  • 41
  • 1
  • 4
  • 1
    Check out these: http://stackoverflow.com/questions/4339649/how-to-have-multiple-colors-in-a-batch-file?lq=1 and http://stackoverflow.com/questions/7923948/batch-color-per-line – gmo Mar 24 '14 at 22:09

1 Answers1

0

I found this batch file a while ago. Unfortunately I can't find the source, or remember who wrote it. Hopefully someone will see this and be able to provide a link.

@echo off
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  set "DEL=%%a"
)
echo next line in another color:
call :ColorText 0c "There is an Ashstorm!"
echo this was red.
call :ColorText 0a "you survived it."

goto :eof

:ColorText
echo off
echo %DEL% > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof

You should be able to adapt it using a for loop to only change the colour of the first line.

Replace this section;

echo next line in another color:
call :ColorText 0c "There is an Ashstorm!"
echo this was red.
call :ColorText 0a "you survived it."

With the following:

set c=1
for /f "delims=" %%a in ('grep -C -i "%1" %2') do (
    if !c!==1 (call :ColorText 02 "%%a") else echo %%a
    set /a c+=1
)
unclemeat
  • 4,691
  • 4
  • 22
  • 49