Last active
September 12, 2018 03:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abc=123 | |
a1=xxx | |
b1=11yy22 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment