Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code for changing colors in batch : How is it working?

Tags:

batch-file

cmd

I found this piece of code which helps to change colors of text output in a batch file. Can someone please explain how it works?

Especially what is the use of DEL variable puzzles me, and without those first lines, the coloring doesn't work at all, but the DEL variable appears to be empty when I echo 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

Also please shed some light on for loop and the ColorText method

like image 889
Subham Tripathi Avatar asked May 04 '15 07:05

Subham Tripathi


1 Answers

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 a <backspace><space><backspace> string, created in the FOR loop by the prompt $H.
This works, as the command block for the for-loop is

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

This sets the prompt first to #<BACKSPACE><SPACE><BACKSPACE>#<ESCAPE># (The escape is senseless here, I just copied it from my string library).
But normally the prompt wouldn't be visible, so I enable ECHO ON and then you need something that the prompt would appear and that will be done with the for %%b in (1) do rem.

The DEL character will be used later as file content.

: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 content of the DEL variable.
The filename is named like the string you want to color.
This is important for the findstr command.

The findstr /v /a:%1 /R "^$" "%~2" nul will be find any line by /R "^$".
As two files are listed (nul is the second filename) each filename will be outputted and colored by the value of /a:%1. As the file NUL has no content it will not be outputted at all.
And the first filename will be outputted also with a colon followed by the file content.

Sample, assume the file content is ABC and the filename is Hello

The output of findstr would be

Hello:ABC

But as I place the <backspace><space><backspace> into the file content the colon will be deleted.

The del "%~2" > nul 2>&1 deletes the temporary file after all.

like image 71
jeb Avatar answered Sep 30 '22 09:09

jeb