我该如何增加一个DOS变量在FOR / F循环? [英] How do I increment a DOS variable in a FOR /F loop?
问题描述
我想从文件中读取文本行,并增加一个计数器,所以我可以最终在DOS模拟阵列。
I'm trying to read text lines from a file, and increment a counter so I can eventually simulate an array in DOS.
我希望能够文本行存放在DOS阵列进行进一步的处理。
I'd like to be able to store the lines of text in a DOS array for further processing.
我现在的尝试是:
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%
)
但变量c不递增;它停留在1。
But the variable c is not incrementing; it stays at 1.
建议表示欢迎。
谢谢,迈克
推荐答案
与code段的问题是变量被扩展的方式。当第一次宣读了一份声明变量扩展通常完成。在你的情况,整个的
回路及其块读取和所有变量,除了循环变量被扩展为当前值。
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.
这意味着%C%
在回声%%我,%C%
瞬间扩大,所以实际上是作为回声%% I,1
在每次循环迭代。
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.
变量,应该是扩大与延迟引用!变量!
而不是的%变量%
。但是,你需要激活与此功能SETLOCAL ENABLEDELAYEDEXPANSION
和匹配 ENDLOCAL
重置。
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
.
您修改code看起来这样的事情:
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
这篇关于我该如何增加一个DOS变量在FOR / F循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!