How do I make one particular line of a batch file a different color then the others?
Asked Answered
F

6

19

I'm working on a program which generates the day's weather for D&D games. I want the program to display a warning in red text when a storm is generated so the DM is aware that this weather is not typical. To reduce the number of keystrokes, it must do this on the same screen as the text detailing the weather itself.

Currently for a storm's entry I have this:

:des4a
cls
type c:\AutoDM\WeatherGen\data\forcast1.txt
color 0c
echo     There is an Ashstorm!
color 0a
echo.
echo     It is %temp% degrees and the sky is invisible threw the thick 
echo     billowing clouds of ash.
echo.
echo         # Survival checks to light a fire are at +15. 
echo         # Small unprotected flames will be snuffed out.
echo         # Non-firearm ranged attacks are at a -8 to hit.
echo         # Preception checks take a -10 for every 10 feet of distance.
echo         # Survival checks to get along in the wild are at +15.
echo         # Stealth checks are at a +5.
echo.
echo     SPECIAL!
echo.
set /a die=6
set /a inches=%random%%%die+1
echo         # The ashstorm will deposit %inches% inches of ash durring its
echo           durration.
echo         # Tracking a target after an ashstorm is at a +15.
type c:\AutoDM\WeatherGen\data\forcast2.txt
echo.
echo.
pause
goto menu

The type commands are calling text documents which contain a header and footer for each entry to help the program look professional and provide a border to assist with word wrap. Thy cannot be removed. DO not suggest something which would make me unable to use the type commands as they currently exist please. Please understand that this red text line will be added to a lot of different parts of the program, each time there is a storm for each and every biome in the generator. I would prefer it to not be more then just 2 or 3 lines of code (But if there is only one way to do it well...)

Can I have the one line in red and the rest in green? Or should I have the program beep to call attention to the fact? Do you have a better and simpler idea? How do I do this?

Franchescafranchise answered 9/2, 2014 at 14:26 Comment(10)
possible duplicate of #2586512Scarborough
@Scarborough No. That is fore more then one color in the same line. I need one line on the screen one color, and the others another color. That answer dose not explain how to implement the code very well ether. Is all of that put down each time you need to use more then one color? Is it put once at the beginning then use command words? Its just not explained well enough for me.Franchescafranchise
It can't be done with simple standard batch commands. An involved script can print color on a single line, or a third party tool can do it. Microsoft color commands only change the entire screen.Hasson
@Hasson I am programming this to be something I am going to attempt to sell. It has to run on any PC. Could you link a tutorial to making such a script?Franchescafranchise
@SeanMcLain - Ummm, just because a solution allows multiple colors on one line doesn't mean you must have multiple colors. The linked solution even explains how to use ECHO( to terminate the line in preparation for the next.Amity
Another question with answers that are basically the same: https://mcmap.net/q/75993/-how-to-have-multiple-colors-in-a-windows-batch-file/1012053Amity
@Amity Ah Its in the code segment itself. That's kinda confusing. thanks dude.Franchescafranchise
Change threw to through and durration to duration.Wobbling
Apparently you are overwriting the system variable temp without even realsing it. Make sure that you are using setlocal at the beginning of your script or even better, use a different variable name.Larcener
Possible duplicate of How to have multiple colors in a Windows batch file?Jecoa
F
38

I was having the same problem yesterday, I did some research and this worked for me. EDIT: This is NOT the same code as the other one.

@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"
)
call :colorEcho 0a "This is colored green with a black background!"
echo.
call :colorEcho a0 "This is colored black with a green background!"
echo.
pause
exit
:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1i

it does this: Output

All you need to do to fit this is put the part from SETLOCAL EnableDel... to ) to the beginning of your code (If your code starts with @echo off then put it under that) and also put the part from :colorEcho to del %~2 at the exact bottom of your script (NOTHING UNDERNEATH!)

Now between you notice

call :colorEcho 0a "This is colored green with a black background!"
echo.
call :colorEcho a0 "This is colored black with a green background!"
echo.
pause
exit

Explained line by line: First line (call :colorEcho 0a "This is colored green with a black background!"): This is a colored echo, it suprisingly says This is colored green with a black background! in 0a (Black Bg, Green Text) Second line (echo.) prints a newline, since our colored echo doesn't print one.

SO

Let's say you wanted to say "Hello World" in Hello being yellow and World being green. Example!

@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"
)
call :colorEcho 0e "Hello "
call :colorEcho 0a " World"
pause
exit
:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1i

This is what it does: Output I hope this is understandable!

EDIT: Make sure the program exits before it could reach :colorEcho

Filide answered 9/2, 2014 at 23:5 Comment(9)
Thank you for the comprehensive answer to my question :3 This will help me in many different areas of the program I am attempting to write. Now that I know how to use this to highlight one word in a sentence for example.Franchescafranchise
Neat, but this can delete files on your disk. Suppose you wanted to display a filename and highlight it (i.e. "c:\output\reports\test.txt"), the code would be... call :colorEcho 0a "c:\output\reports\test.txt" The last line of :colorEcho ... del "%~2" .... would delete the file if it actually existed.Debag
From all the mathods I saw on SO your is easiest to understand and short. TYBromate
Not that you would need to, but you can put code below the colorEcho subroutine if you cap it off with exit /bHydrocarbon
Is it possible to have special characters in the highlighted line? For example this works: call :colorEcho 0e "anthing I can help with" But this doesn't: call :colorEcho 0e "anthing else I can help with?"Schwarz
Very good solution. My problem is I get two dots in front of each text echo command.Rotund
Very good solution. My problem is I get two unwanted,excess, horizontal dots in front of colored result text. For example Hello. . do you have any suggestions? I even copy pasted your code into a new file and I still see the problem.Rotund
Not sure who came up with this idea originally, but there are various posts around that predates this one. Excellent, though! Small issue: your post calls colorEcho with an exclamation mark, but this mark is not output (and two other points: doesn't work with single dot ., or if files already exist the results are disastrous, but this is easy to work around).Dominik
For everyone trying to paint something fancy with this. You need to avoid characters like :, /, \ that let your string look like a path (this also reffers to . and ..) and also avoid wildcards like *. Note that you can't use trailing whitespace. Happy painting ;)Doak
S
2

Script from here: How to have multiple colors in a Windows batch file? a little modified (simplyfied):

@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

It was a link in the very first answer of "possible duplicate: How to change the text color of comments line in a batch file "

Scarborough answered 9/2, 2014 at 15:9 Comment(6)
Ok so, this goes at the beginning of the batch file. Ok. But how do I get it to work at many different places within the file, not just one? I need to know how to use the code as well as what the code is. I'm only semi literate in Batch.Franchescafranchise
@SeanMcLain: the first lines (the forcommand) just generates a variable, you have to do this only once. The code starting with :ColorText and ending with goto :eof is a "subroutine". You also need this only one time. You can call it where and as often as you need it.Scarborough
Ah thank you! So if I want to have multiple colors available to use other then the "base" color say, cyan, I would add a duplicate of this for each color, changing 0a to 0c for cyan and so on? ALso where is :eof ? I cant find that label and its going to break my code if I run it as is right? Do I change the label to one at the start of my program? Tried it, I had to make it "goto :menu" or it wouldn't run at all. and in the instance where the call command is, I get an error message about it being an invalid command :/Franchescafranchise
No. Just change the parameter: call :ColorText 0c "red Text" or `call :ColorText 0a "green text"' I edited my answer to show you.Scarborough
Yeah this docent work at all... Or at least not how I am doing it :/ It ether wont run or will display an error message, not text in red, then the rest of the text which should be on screen.Franchescafranchise
@Sean: Perhaps you should take the example above and paste it into its own batch file and run it. You'll see that it does work, so the changes you are making are breaking it. Regarding :eof, that's a built-in label that means the end of a file, and that is perhaps the most important part of a subroutine. Don't change it.Wobbling
T
0
@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"
)
call :colorEcho 0c "HyperBeast"
echo.
call :colorEcho 0c "NeonRider"
echo.
call :colorEcho 0d "Djinn"
echo.
call :colorEcho 0d "Eco"
echo.
call :colorEcho 0d "MonkeyBuisness"
echo.
call :colorEcho 05 "GrandPrix"
echo.
call :colorEcho 05 "PolePosition"
echo.
call :colorEcho 05 "Heat"
echo.
call :colorEcho 05 "WormGod"
echo.
call :colorEcho 09 "Origami"
echo.
call :colorEcho 09 "Man'o'war"
echo.
call :colorEcho 09 "Valence"
echo.
call :colorEcho 09 "BronzeDeco"
echo.
call :colorEcho 09 "ArmorCore"
echo.
call :colorEcho 09 "EliteBuild"
echo.
pause
exit
:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1\
Tweeddale answered 22/4, 2015 at 3:6 Comment(0)
F
0

You can try this script. Use it to print any text with any color in any screen position. It does not use temporary files, but your system must have debug.exe executable (Windows native):

@echo off
rem Script written by BrendanSilva [bl8086]
rem You need DEBUG.EXE executable in your system.
setlocal enabledelayedexpansion
set /a _er=0
set /a _n=0
set _ln=%~4
goto init
:howuse ------------------------------------------------------------------------
    echo.
    echo ECOL.BAT - v2.0
    echo Print colored text as batch script without temporary files.
    echo Written by bl8086
    echo.
    echo Syntax:
    echo ECOL.BAT [COLOR] [X] [Y] "Insert your text here"
    echo COLOR value must be a hexadecimal number like "color /?" information
    echo.
    echo Example:
    echo ECOL.BAT F0 20 30 "640K ought to be enough for anybody."
    echo.
    goto :eof
:error ------------------------------------------------------------------------
    set /a "_er=_er | (%~1)"
    goto :eof
:gcnvhx ------------------------------------------------------------------------
    set _cvhx=
    set /a _cvint=%~1
:cnvhx
    set /a "_gch = _cvint & 0xF"
    set _cvhx=!nsys:~%_gch%,1!%_cvhx%
    set /a "_cvint = _cvint >> 4"
    if !_cvint! neq 0 goto cnvhx
    goto :eof
:init --------------------------------------------------------------------------
    if "%~4"=="" call :error 0xff
    (
        set /a _cl=0x%1
        call :error !errorlevel!
        set _cl=%1
        call :error "0x!_cl! ^>^> 8"
        set /a _px=%2
        call :error !errorlevel!
        set /a _py=%3
        call :error !errorlevel!
    ) 2>nul 1>&2
    if !_er! neq 0 (
        echo.
        echo ERROR: value exception "!_er!" occurred. Check memory out.
        echo.
        goto howuse
    )
    set nsys=0123456789ABCDEF
    set /a cnb=0
    set /a cnl=0
    set _cvhx=0
    set _cvint=0
    set _cvmhx=0
:parse -------------------------------------------------------------------------
    set _ch=!_ln:~%_n%,1!
    if "%_ch%"=="" goto perform
    set /a "cnb += 1"
    if %cnb% gtr 7 (
        set /a cnb=0
        set /a "cnl += 1"
    )
    set bln%cnl%=!bln%cnl%! "!_ch!" %_cl%
    set /a "_n += 1"
    goto parse
:perform -----------------------------------------------------------------------
    set /a "in = ((_py * 0xA0) + (_px << 1)) & 0xFFFF"
    call :gcnvhx %in%
    set ntr=!_cvhx!
    set /a jmp=0xe
    set bl8086str=echo.h 0 0
    @for /l %%x in (0,1,%cnl%) do (
        set bl8086str=!bl8086str!^&echo.eb800:!ntr! !bln%%x!
        set /a "in=!jmp! + 0x!ntr!"
        call :gcnvhx !in!
        set ntr=!_cvhx!
        set /a jmp=0x10
    )
    (
    echo %bl8086str%
    echo.q
    ) |debug >nul 2>&1
Flied answered 11/11, 2016 at 15:46 Comment(0)
L
0

Old school trick:

echo =======================================================================================================================
echo [37m[0;1;36m*************************************************************************
echo    *****   *****   *****   [31mWiindows 10 Networking  [36m*****   *****   *****
echo *************************************************************************[37m[0;1;37m
echo echo [37m[0;1;32m
echo =======================================================================================================================

cut and paste - I never could find doc's on this type of coding [?] used to be a forward arrow in DOS it was fun in my Autoexec,bat file. hope it helps some hacker - they sure have helped me, Thanks!

Lawmaker answered 17/2, 2023 at 22:11 Comment(0)
N
0

Ok so for anyone that manages to read down this far, BOTH suggestions of the presented scripts are the best solution. The first script can be used for a single line when changing colors of just a single word of text and requires a space at the end and at the beginning of each new call. however it continues the next command in the seques right after the text, Same happens if you want to add a return some where to mark a new line. So that is where we use the second iteration of the colorEcho, for this I added an "r" to the end, here is a sample that works. HOWEVER, special characters do not work, you can use periods, no questionmarks.

    @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
)

call :colorEchor 07 "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
call :colorEcho 07 "~~~~~~~~~~~~~~~~~~~~~~~~~~~This is color "
call :colorEcho 02 " ONE "
call :colorEcho 07 " and this is color "
call :colorEcho 0b " TWO "
call :colorEchor 07 " ~~~~~~~~~~~~~~~~~~~~~~"
call :colorEchor 07 "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
pause





rem Scripts and everything go within this blank block and all text still works just fine calling for the 2 types of colorEcho and ColorEchor






EXIT


:colorEcho
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1i
GOTO :EOF

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

:EOF
Newtonnext answered 12/8, 2024 at 19:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.