简体   繁体   中英

batch script how to recognize a variable from string

I want batch script to read vars from a config file.
And I want to use var in the config file.
So I put the content below into my config file eval.ini :

Universal:=C:\Universal
Galaxy:=%Universal%\Galaxy
Sagittarius:=%Universal%\Sagittarius
Canis Major:=%Universal%\Canis Major
Sun:=%Galaxy%\Sun
Sirius:=%Canis Major%\Sirius

So how can I make these vars in config file be recognized by batch script.


In the moment, how I make it work is to read "eval.ini" line by line, and split one line become a var name and a var value.

Galaxy:=%Universal%\Galaxy    ==>>    Galaxy    %Universal%\Galaxy

And put them into a temp batch script mixed likd this:

SET "Galaxy=%Universal%\Galaxy"

And then I call the temp batch script, to set all the vars. And it works.

It seems OK but I just don't like to create an temp batch script file to do this.
Please tell me any other way to do this.


My batch script "eval.bat":

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

:SOA
    SET "confile=%~dpn0.ini"
    SET "setvar=%temp%\%~n0_setvar.bat"
    SET "varlist="

    ECHO/>%setvar%
    FOR /F "usebackq tokens=1,* eol=; delims=:=" %%a in ("%confile%") do (
        IF NOT "!varlist!" == "" (
            SET "separator= "
        ) else (
            SET "separator="
        )
        SET "varlist=!varlist!!separator!^"%%a^""
        ECHO/SET "%%a=%%b">>%setvar%
    )
    CALL "%setvar%" && del/q/f "%setvar%" || GOTO:EOA
    FOR %%a in (%varlist%) do (
        ECHO/%%~a = !%%~a!
    )

:EOA
    ENDLOCAL
    EXIT/B

OUTPUT:

Universal = C:\Universal
Galaxy = C:\Universal\Galaxy
Sagittarius = C:\Universal\Sagittarius
Canis Major = C:\Universal\Canis Major
Sun = C:\Universal\Galaxy\Sun
Sirius = C:\Universal\Canis Major\Sirius
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

:SOA
SET "confile=q24928414.txt"
SET "setvar=%temp%\%~n0_setvar.bat"
SET "varlist="

FOR /F "usebackq tokens=1*delims=:=" %%a in ("%confile%") do (
 CALL SET "%%a=%%b"
 ECHO %%a = !%%a!
)

:EOA
GOTO :EOF

I replaced your input file with q24928414.txt to suit my system.

Works for me!

-- edited following MC ND 's response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM