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
Asked
Active
Viewed 65 times
1

Nathan Tuggy
- 2,237
- 27
- 30
- 38

Bob
- 109
- 1
- 8
-
1The complete rules for this type of managements are described at [this post](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990); you just need to change "array element" by "substring" in that description... – Aacini Aug 10 '15 at 04:36
1 Answers
3
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

SomethingDark
- 13,229
- 5
- 50
- 55