Skip to content

Instantly share code, notes, and snippets.

@vikyd
Last active September 12, 2018 03:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vikyd/13635182f0092ff1e9a3e1f543f88123 to your computer and use it in GitHub Desktop.
Save vikyd/13635182f0092ff1e9a3e1f543f88123 to your computer and use it in GitHub Desktop.
Windows Batch: get value from key=value file with value trim, not allow `=` in value, not allow space after or before the key
@ECHO OFF
REM https://stackoverflow.com/a/9681923/2752670
SET myKey=abc2
SET myFile=keyval.txt
CALL :GetVal %myFile% %myKey% myVal
REM is string empty https://stackoverflow.com/a/2541820/2752670
IF [%myVal%] == [] (
ECHO no key: %myKey% in file: %myFile%
) ELSE (
ECHO %myVal%
)
EXIT /B
REM -------------------------------------------
REM equal sign `=` is not allow inside value
:GetVal
SetLocal EnableDelayedExpansion
FOR /F "tokens=1,2 delims==" %%i IN (%1%) DO (
IF "%%i" == "%2%" (
SET val=%%j
)
)
SET ValOk=
REM https://stackoverflow.com/a/8602078/2752670
IF DEFINED val (
CALL :Trim ValOk !val!
REM ECHO -!ValOk!-
REM ECHO -!val!-
)
EndLocal & SET %3=%ValOk%
GOTO:EOF
REM https://stackoverflow.com/a/26079981/2752670
:Trim
SetLocal EnableDelayedExpansion
SET Params=%*
FOR /F "tokens=1*" %%a IN ("!Params!") DO EndLocal & SET %1=%%b
GOTO:EOF
abc=123
a1=xxx
b1=11yy22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment