使用DOS批处理脚本计数在for循环 [英] Counting in a FOR loop using DOS Batch script
问题描述
有人能解释一下吗?我可以用DOS循环来算,使用此方法:
SET / A XCOUNT = 0
:循环
SET / A XCOUNT + = 1
回声%XCOUNT%
IF%XCOUNT%==4(
GOTO结束
)ELSE(
GOTO循环
)
:结束
但这种方法不能正常工作(它打印出1文件中的每一行)。它就像变量超出范围:
SET / A COUNT = 1
FOR / F令牌= *%% A IN(config.properties)DO(
SET / A COUNT + = 1
ECHO%COUNT%
)
它不工作,因为的全部的为
环路(含中的命令它)正在评估的时候遇到过,的前的它开始执行。
在换句话说,%计%
替换其值 1
之前运行的循环。
您需要的是这样的:
SETLOCAL ENABLEEXTENSIONS enabledelayedexpansion
SET / A COUNT = 1
FOR / F令牌= *%% A IN(config.properties)DO(
SET / A COUNT + = 1
ECHO!算!
)
ENDLOCAL
延迟扩展使用!
而不是%
会给你预期的行为。参见<一个href=\"http://stackoverflow.com/questions/5349153/strange-question-about-windows-batch-file/5349159#5349159\">here.
Can anyone explain this? I am able to count in a loop using DOS, using this method:
SET /A XCOUNT=0
:loop
SET /A XCOUNT+=1
echo %XCOUNT%
IF "%XCOUNT%" == "4" (
GOTO end
) ELSE (
GOTO loop
)
:end
But this method does not work (it prints out "1" for each line in the file). It acts like the variable is out of scope:
SET /A COUNT=1
FOR /F "tokens=*" %%A IN (config.properties) DO (
SET /A COUNT+=1
ECHO %COUNT%
)
It's not working because the entire for
loop (including the commands within it) is being evaluated when it's encountered, before it begins executing.
In other words, %count%
is replaced with its value 1
before running the loop.
What you need is something like:
setlocal enableextensions enabledelayedexpansion
SET /A COUNT=1
FOR /F "tokens=*" %%A IN (config.properties) DO (
SET /A COUNT+=1
ECHO !COUNT!
)
endlocal
Delayed expansion using !
instead of %
will give you the expected behaviour. See also here.
这篇关于使用DOS批处理脚本计数在for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!