I have a batch program and I want the for loop to split a string by a delimiter, so a substring is split and printed out in each iteration.
However, I found the for loop does not repeat as expected but just executes for only once, although the variable my_str
does change its value correctly.
So what are the causes of problems?
PS:
FYI, the number of substrings in my_str
variable will be unknown, so I did not use token
option in for loop.
My batch program:
@echo off
setlocal enabledelayedexpansion
set "my_delim=`"
set "my_str=I am A`I am B`I am C`"
for /F "delims=%my_delim%" %%A in ("!my_str!") do (
echo inside loop started
echo A value is [%%A]
set "my_str=!my_str:*%my_delim%=!"
echo remaining my_str is [!my_str!]
echo inside loop ended
echo ------------------------------------
)
echo exited loop
pause
Actual result:
inside loop started
A value is [I am A]
remaining my_str is [I am B`I am C`]
inside loop ended
------------------------------------
exited loop
Press any key to continue . . .
Expected result:
inside loop started
A value is [I am A]
remaining my_str is [I am B`I am C`]
inside loop ended
------------------------------------
inside loop started
A value is [I am B]
remaining my_str is [I am C`]
inside loop ended
------------------------------------
inside loop started
A value is [I am C]
remaining my_str is []
inside loop ended
------------------------------------
exited loop
Press any key to continue . . .