SETLOCAL EnableDelayedExpansion
SET str=123456789abcdefgh
FOR /l %%x IN (1, 1, 10) DO (
SET /a intLength=10-%%x
SET result=!str:~-%%x!
ECHO "Works as intended: " !result!
SET result=!str:~-intLength!
ECHO "Does NOT work as intended: " !result!
)
endlocal
You're using the literal string intLength
instead of the %intLength%
variable.
Since you're initializing a variable inside of a for loop, you're going to have to use the !intLength!
variation of this variable name. Unfortunately, since you're already using exclamation points to get the substring from str
, you can't also use them in that line to get the value of intLength
, since you'd then essentially have a variable !str:~!
, an unrelated string that batch really isn't going to like, and a !!
.
You can get around this by running !intLength!
through another for loop and using the %%var
variable instead, since you've already shown that that works.
@echo off
setlocal EnableDelayedExpansion
set str=123456789abcdefgh
for /l %%x in (1, 1, 10) DO (
set /a intLength=10-%%x
SET result=!str:~-%%x!
echo Works as intended: !result!
for /f %%A in ("!intLength!") do SET result=!str:~-%%A!
echo Now works as intended: !result!
echo.
)
endlocal
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.