But an extra double quotes("") appear after the last echo.
I solved it with a "rem", but not sure what causes it. So, what causes those quotes?
Also, how to write this code elegantly, with less delayed expansion variables and better escaping?
Code: Select all
@echo off
setlocal enableDelayedExpansion
(set \n=^^^
%= This creates an escaped Line Feed - DO NOT ALTER =%
)
set "quot.=""
set "quot=^!quot.^!"
(set text.=11x y z%\n%
22d e f%\n%
33q w x)
rem A simple loop
for /F "tokens=1-2 skip=1 delims= " %%G in ("!text.!") do (echo %%G -- %%H)
set "param=tokens=1-2 skip=1 delims= "
set "text=^!text.^!"
echo --- Dynamic Loop ---
rem It does not work when there are parenthesis after "do", raises error : "" was unexpected at this time.
rem call :myloop "for /F !quot!!param!!quot! %%%%G in ("!text!") do ( echo %%%%G --- %%%%H )"
rem Without parenthesis, extra double quotes("") at the end, solved by rem, set a= etc.
rem call :myloop "for /F !quot!!param!!quot! %%%%G in ("!text!") do echo %%%%G --- %%%%H && rem"
rem With parenthesis, rem also solves the double quote problem.
call :myloop "for /F !quot!!param!!quot! %%%%G in ("!text!") do (echo %%%%G --- %%%%H ) && rem"
rem Following works fine with separate parameters, so quoting of options handled in the routine
rem call :myloop2 "echo for loop && for /F" "!param!" "%%%%G in ("^!text^!") do (echo %%%%G --- %%%%H)"
endlocal
goto :eof
:myloop
setlocal
set "str=%~1"
%str%
endlocal
exit /b
goto :eof
:myloop2
setlocal
%~1 "%~2" %~3
endlocal
exit /b
goto :eof