title: Windows batch: delayed expansion in a for loop
body: <p>I want to modify a few specific lines of numbers of text files, and I wrote a batch file as follows:</p>
  
  <pre><code>@echo off
  set n=0
  set n1=10
  set n2=40
  cd.&gt;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!)&gt;&gt;output.txt
  endlocal
  )
  start output.txt
  </code></pre>
  
  <p>However, this doesn't work as expected.<br>
  After some tests, I think the <code>!n!</code> expansion is not normally delayed. That is very strange, because <code>!var!</code> expansion is normally delayed.</p>
  
  <p>By the way, the <code>setlocal enabledelayedexpansion</code> and <code>endlocal</code> commands are put in the <code>for</code> loop, because otherwise the special character <code>!</code> will be abandoned.</p>