Reputation: 93
I want to modify a few specific lines of numbers of text files, and I wrote a batch file as follows:
@echo off
set n=0
set n1=10
set n2=40
cd.>output.txt
for /f "delims=" %%i in ('findstr /n .* test.txt') do (
set "var=%%i"
setlocal enabledelayedexpansion
set /a n=!n!+1
echo.!n!
set var=!var:*:=!
rem if !n!=%n1% ...
rem if !n!=%n2% ...
(echo.!var!)>>output.txt
endlocal
)
start output.txt
However, this doesn't work as expected.
After some tests, I think the !n!
expansion is not normally delayed. That is very strange, because !var!
expansion is normally delayed.
By the way, the setlocal enabledelayedexpansion
and endlocal
commands are put in the for
loop, because otherwise the special character !
will be abandoned.
Upvotes: 2
Views: 4056
Reputation: 82307
I suppose the problem what you see is that n
will never increase.
But that isn't a problem of the delayed expansion, it's an effefct of the setlocal/endlocal
block inside the loop.
As @panda-34 mentioned you should use the extended syntax of set/a
and move the statement outside the setlocal/endlocal
block.
@echo off
set n=0
set n1=10
set n2=40
(
for /f "delims=" %%i in ('findstr /n .* test.txt') do (
set "var=%%i"
set /a n+=1
setlocal enabledelayedexpansion
echo !n!
set var=!var:*:=!
rem if !n!=%n1% ...
rem if !n!=%n2% ...
(echo(!var!)
endlocal
)
) >output.txt
start output.txt
Upvotes: 3