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 a DOS array for further processing.
My current attempt is:
set TEXT_T="myfile.txt"
set /a c=1
FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
set /a c=c+1
echo %%i, %c%
)
But the variable c is not incrementing; it stays at 1.
Suggestions welcome.
Thanks, Mike
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 yourecho %%i, %c%
expanded instantly and so is actually used asecho %%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 withsetlocal ENABLEDELAYEDEXPANSION
and reset it with a matchingendlocal
.Your modified code would look something like that:
What about this simple code, works for me and on Windows 7
Using Windows 7. Can't get the
EnableDelayedExpansion
to do its thing. I have two test files calledTest1.tst
andTest2.tst
. I want to do something with only the first one. The two places I the '!' doesn't resolved to the value. The lastecho
prints zero. Here is my code:Or you can do this without using Delay.
-> your for loop here
I would like to add that in case in you create local variables within the loop, they need to be expanded using the bang(!) notation as well. Extending the example at https://stackoverflow.com/a/2919699 above, if we want to create counter-based output filenames