I'm writing a batch script to read from a file. The file contains lines such as token=value. I have code to parse each line of the file and it is stored in %%i. The following code tries to extract the value of token:
Take note that this script is using delayed expansion, as mentioned in the comments.
for /f "tokens=1* delims==" %%a in ("%%i") do (
if "%%a"=="password" ( set password=%%b )
)
If value of token password contains "!", then the "!" is skipped and only rest of the string is stored in variable password. Example, if the line is:
password=Test!
then variable password=Test . I have tried to change the input file various ways and batch script reads everything except "!". I have used:
password=Test%!
password=Test%!
and everything skips "!". Any idea how I can read a string with "!" into a variable?
Assuming you're using delayed variable expansion just disable it temporarily for the comparison. To compare in the non-delayed mode I'd parse the current line splitting by !
and check if the first token is the same as the entire line:
@echo off
setlocal enableDelayedExpansion
for /f "delims=" %%i in (sourcefile.txt) do (
setlocal disableDelayedExpansion
for /f "delims=! tokens=1" %%z in ("%%i") do (
if "%%z"=="%%i" ( rem The line has no !
for /f "tokens=1* delims==" %%a in ("%%i") do (
if "%%a"=="password" ( set "password=%%b" )
)
)
)
endlocal
)
pause
However password
variable will be only available in the inner setlocal context, to export it use that answer .
I am not experiencing that problem with the code you posted. I think the error may precede the code you posted which stores each line of the file in %%i.
Put an echo statement in there before your %%a loop so that you can verify the contents of %%i before processing further. I highly suspect that the exclamation point isn't making it into %%i in the first place.
Here is the full CMD file I ran on Windows 7:
@echo off
for /f "tokens=1* delims= " %%i in ("password=Test!") do (
echo i: %%i
for /f "tokens=1* delims==" %%a in ("%%i") do (
if "%%a"=="password" ( set password=%%b )
)
)
echo password: %password%
The output is as follows:
i: password=Test!
password: Test!
So you can see that Test!
is making it through the for loop intact when %%i contains password=Test!
. If you want to post the earlier pieces of your batch file, we can help you troubleshoot further.
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.