Reputation: 1422
I'm a Perl programmer, but I need to do a Windows batch file for a particular task.
The script needs to read an input file line by line, and copy to an output file. However part way through, it needs to switch output files.
For reading an input file and outputing to a file generally, the solution in the following article by Jeb seems to work best. (Other solutions don't work well when the input data has weird characters or long lines) Batch files: How to read a file?
However I can't get it to work where I change the outputfile mid-way. The problem is probably with the way DelayedExpansion works.
When I run the following script, outfile at the end is still a.txt, and new_variable is not set.
@echo off
del /f/q a.txt
del /f/q b.txt
del /f/q c.txt
del /f/q out.txt
set outfile=a.txt
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ in.txt"`) do (
set "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
IF "!%var!" == "/************************** PLUGINS SECTION *************************/" (
set outfile=b.txt
set new_variable=this
echo "FOUND! Value of outfile should change to b.txt"
)
echo( !outfile! !var! >>!outfile!
ENDLOCAL
)
echo Outfile: %outfile%
echo New Variable: %new_variable%
Upvotes: 1
Views: 3006
Reputation: 82247
You loose your variable changes after the endlocal.
So you need to save the values over the endlocal
barrier.
The easiest way here is to use the FOR-Endlocal
technic.
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ in.txt"`) do (
set "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
if "!var!" == "****" (
set outfile=b.txt
set new_variable=this
)
FOR /F "tokens=1,2" %%O in (!outfile! !new_variable!) DO
(
ENDLOCAL
set "outfile=%%O"
set new_variable=%%P
)
)
This works as the %%O and %%P parameters of the FOR-loop are not affected by the ENDLOCAL
.
Both values are cached over the barrier.
Upvotes: 1