K
K
Kovalsky2016-09-07 14:55:35
cmd/bat
Kovalsky, 2016-09-07 14:55:35

How to change line color in CMD?

I myself don’t understand a damn thing in cmd, so I looked for a solution on the Internet.
As far as I understand, color is not used for this. it changes color throughout the session. But they use some kind of hack with the findstr command , which can explicitly specify the color of the message it displays.
Here's what dug up:

:write
  setlocal
  :write1
  set "tempFolder=%TEMP%\%~n0.%time:~-2%.%random%"
  md "%tempFolder%" 2>nul || goto write1
  pushd %tempFolder%
  set /p .=.<nul>"%~2"
  findstr /a:%~1 /c:"." /s "%~2"
  popd
  rd /s /q "%tempFolder%" 2>nul
endlocal & exit /b

:writeLn
  call :write %1 "%~2"
  echo:
exit /b

This stuff works almost exactly as it should, except it adds a colon and a period at the end. That is, the call call :write 0A "My Charona"will return My Charona:., where My Charona and the colon will be green, and the period will be the default.
Some lines of code are almost clear to me ( findstr /a:%~1 /c:"." /s "%~2"), some are black magic ( set /p .=.<nul>"%~2").
Is there any way to get rid of the last two characters in the string output by findstr ?
By the way, yes: if you remove all operations with directories from the code, the functionality does not change at all, everything works the same.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
wisgest, 2019-05-24
@lazalu68

CMD/BAT: Display colorful text

A
Alexey, 2016-09-07
@skazi_premiere

Is that not an option?ef1963e851954a5c8112cbc23c1bb387.png662c74dcb6e4422bb586a664b3ba4da7.png

R
res2001, 2016-09-07
@res2001

set /p .=.<nul>"%~2"- writes a dot to the file "%~2" without a newline.
The standard option echo .>"%~2"is to add line feed/carriage return characters at the end of the file.
findstr /a:%~1 /c:"." /s "%~2"- searches for a point in the file "%~2" and displays it in the color specified in "%~1". Due to the presence of the /s key, the name of the file in which the point was found is displayed, and the previous command creates a file with a name equal to the search phrase, i.e. the effect of the output of the phrase is created.
You can get rid of the dot by replacing it with a space, but I don’t think you can get rid of the colon.
In general, this does not look like a normal way of output. If you really want colored letters in a batch file, then look towards nircmd or similar multifunctional command line utilities, perhaps there is such a feature there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question