How can I use command line arguments to control a batch program that prints multi-colour text?

前端 未结 2 1911
野性不改
野性不改 2020-12-21 17:18

I have a batch script that can display two or more colors of text on the same line in the command prompt. (below)

@echo off
SETLOCAL EnableDelayedExpansion
f         


        
相关标签:
2条回答
  • 2020-12-21 17:53

    EDIT: Take 3

    Create the folder C:\Utilities. Add this folder to your Path environment variable so Windows looks there for additional scripts and commands.

    1. Open Control Panel, System, Advanced System Settings (or "Advanced" in Windows XP), Environment Variables.
    2. In the "System variables" list, select the "Path" variable.
      Do not mess these next steps up!
    3. Press Edit.
    4. Place the cursor at the end of the line and make sure no text is selected.
    5. Add the text ;C:\Utilities, including the semi-colon. Do not remove any other text.
    6. Press OK.
      Breathe easy again.
    7. Press OK as many times as necessary to close all windows.

    Take the script following the :ColorText label and save it to C:\Utilities\cecho.bat. Put an @ in front of echo off to prevent echo off from appearing during the script.

    CEcho.bat

    @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"
    )
    <Nul Set /p ".=%DEL%" > "%~2"
    FindStr /v /a:%1 /R "^$" "%~2" Nul
    Del "%~2" > Nul 2>&1
    EndLocal
    

    Now you can use this command from any command line or script. Usage:

    CEcho color "text"
    

    Edit: In response to your comment:

    You can use words for colours by inserting the following lines and replacing the FindStr line:

    Set Color=%1
    If %1==blue Set Color=9
    If %1==red Set Color=C
    etc...
    FindStr /v /a:%Color% /R "^$" "%~2" Nul
    

    Now you can type:

    CEcho red "apple"
    CEcho blue "water"
    CEcho A "grass"
    CEcho 6 "dirt"
    CEcho 26 "tree"
    

    Note that the color word is case sensitive.

    0 讨论(0)
  • 2020-12-21 17:53

    You could use the batch parameters %1, %2, ..., %n, as parameter for the color and for the content

    cecho 0a "hello world!"

    @echo off
    call :ColorText %1 "%~2"
    ...
    

    If you want to use the color names you have to convert them to the corresponding number.

    cecho blue "hello"

    @echo off
    if "%1"=="red" set color=0c
    if "%1"=="blue" set color=0b
    if ...
    call :ColorText %color% "%~2"
    
    0 讨论(0)
提交回复
热议问题