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
A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.
If you declare it inside, it will be a new variable each time it iterates. When that is done, you will need to increment the variable for each iteration, this can be done by either $i++ or $i+=1 . If you wish it to start with 1 and the increase, set it to 1 from start and increase it by 1 at the end of the loop.
To prevent being bitten by artifacts of floating point arithmetic, you might want to use an integer loop variable and derive the floating point value you need inside your loop: for (int n = 0; n <= 40; n++) { double i = 0.25 * n; // ... }
Increment is an expression that determines how the loop control variable is incremented each time the loop repeats successfully (that is, each time condition is evaluated to be true).
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
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
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 set OUTPUT_FILE_NAME=output_!c!.txt echo Output file is !OUTPUT_FILE_NAME! echo %%i, !c! ) endlocal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With