How do I increment a DOS variable in a FOR /F loop?

后端 未结 5 1641
后悔当初
后悔当初 2020-12-13 00:02

I\'m trying to read text lines from a file, and increment a counter so I can eventually simulate an array in DOS.

I\'d like to be able to store the lines of text in

5条回答
  •  猫巷女王i
    2020-12-13 00:39

    The problem with your code snippet is the way variables are expanded. Variable expansion is usually done when a statement is first read. In your case the whole FOR loop and its block is read and all variables, except the loop variables are expanded to their current value.

    This means %c% in your echo %%i, %c% expanded instantly and so is actually used as echo %%i, 1 in each loop iteration.

    So what you need is the delayed variable expansion. Find some good explanation about it here.

    Variables that should be delay expanded are referenced with !VARIABLE! instead of %VARIABLE%. But you need to activate this feature with setlocal ENABLEDELAYEDEXPANSION and reset it with a matching endlocal.

    Your modified code would look something like that:

    set TEXT_T="myfile.txt"
    
    set /a c=1
    
    setlocal ENABLEDELAYEDEXPANSION
    
    FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
      set /a c=c+1
    
      echo %%i, !c!
    )
    
    endlocal
    

提交回复
热议问题