Code for changing color in a batch: how does it work?

I found this piece of code that helps change the colors of text output in a batch file. Can someone explain how this works?

In particular, that the use of the DEL variable is starving me, and without these first lines the coloring does not work at all, but the DEL variable seems empty when I repeat it.

 @echo on 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" ) call :ColorText 0b "red" echo( call :ColorText 19 "yellow" goto :eof :ColorText echo off <nul set /p ".=%DEL%" > "%~2" findstr /v /a:%1 /R "^$" "%~2" nul del "%~2" > nul 2>&1 goto :eof 

I also ask you to shed light on the for loop and the ColorText method

+5
source share
1 answer
 for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do ( set "DEL=%%a" ) 

After this block, the DEL variable contains the string <backspace><space><backspace> created in the FOR loop using prompt $H
This works because the command block for the for loop

 prompt #$H#$E# echo on for %%b in (1) do rem 

The request is first #<BACKSPACE><SPACE><BACKSPACE>#<ESCAPE># (escape is pointless here, I just copied it from my string library).
But usually the invitation will not be visible, so I turn on ECHO ON , and then you need something that the invitation will appear, and this will be done with for %%b in (1) do rem .

The DEL character will be used later as the contents of the file.

 :ColorText <nul set /p ".=%DEL%" > "%~2" findstr /v /a:%1 /R "^$" "%~2" nul del "%~2" > nul 2>&1 

The first line of this function creates a file with the contents of the DEL variable.
The file name is called the string you want to mark.
This is important for the findstr command.

findstr /v /a:%1 /R "^$" "%~2" nul will find any string /R "^$" .
Since two files are listed (nul is the second file name), each file name will be displayed and colored with /a:%1 . Since the NUL file has no content, it will not be displayed at all.
And the first file name will also be displayed as a colon, followed by the contents of the file.

Example, suppose the contents of the file are ABC and the file name is Hello

The result of findstr will be

 Hello:ABC 

But when I put <backspace><space><backspace> in the contents of the file, the colon will be deleted.

del "%~2" > nul 2>&1 still deletes the temporary file.

+6
source

All Articles