Page 1 of 1
Is it possible to pull variable out of setlocal and endlocal pair in for loop
Posted: 07 May 2019 13:55
by sincos2007
Code: Select all
:test5
setlocal DisableDelayedExpansion
set /a "n=0"
for /f "delims=" %%i in (txt1.txt) do (
set "line=%%i"
setlocal EnableDelayedExpansion
set "str_out=!str_out! / number{!n!}-{!line!}"
rem debug
echo !str_out!
endlocal&set "str_out_1=%str_out%"
set /a "n+=1"
echo Position 1:
echo str_out_1=%str_out_1%
)
echo Position 2:
echo str_out_1=%str_out_1%
endlocal
goto :eof
I always feel there has a way to reach this title, without help of io redirection. I believe for loop is powerful.
Re: Is it possible to pull variable out of setlocal and endlocal pair in for loop
Posted: 29 Jul 2019 09:21
by Eureka!
Assuming this is an XY-problem:
Easiest way that I know is replacing the
for ... DO ( <lots of commands> ) with:
for ... DO call :label.
That will even get rid of the setlocal/endlocal pair.
I didn't understand what you were trying to accomplish, but this should give you some inspiration:
Code: Select all
@echo off
setlocal
set /a "n=0"
for /f "delims=" %%i in (lijst.txt) do call :LINE "%%i"
:: Show vars
set str_out
goto :EOF
::______________________________________________
::
:LINE
::______________________________________________
::
set line=%~1
set str_out_%n%=/ number{%n%}-{%line%}
set str_out=%str_out% / number{%n%}-{%line%}
set /a "n+=1"
goto :eof
OUTPUT:
Code: Select all
str_out= / number{0}-{texta} / number{1}-{textb} / number{2}-{textc}
str_out_0=/ number{0}-{texta}
str_out_1=/ number{1}-{textb}
str_out_2=/ number{2}-{textc}
call :LINE "%%i" passes the current line as a parameter to the :LINE routine.
Inside the :LINE routine it is available as
%1
Wrap parameters in "" (because of spaces and "dangerous" characters); unwrap them in the :LINE routine.
EDIT: forgot to show the 'lijst.txt' inputfile: