使用Windows批处理脚本在FOR循环中计数 [英] Counting in a FOR loop using Windows Batch script
问题描述
任何人都可以解释一下吗?我可以使用Windows命令提示符,使用这种方法计数循环:
Can anyone explain this? I am able to count in a loop using the Windows command prompt, using this method:
SET /A XCOUNT=0
:loop
SET /A XCOUNT+=1
echo %XCOUNT%
IF "%XCOUNT%" == "4" (
GOTO end
) ELSE (
GOTO loop
)
:end
不工作(它为文件中的每一行打印出1)。它的行为就像变量超出范围:
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%
)
推荐答案
它不工作,因为 c>循环(从
到到最后右括号,包括之间的命令)正在被评估, 开始执行。
It's not working because the entire for
loop (from the for
to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.
换句话说,%count%
你需要的是:
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.
还要记住, setlocal / endlocal
实际上限制了内部改变的范围,不漏出。如果您想在 endlocal
之后使用 count
,您必须使用 你可能遇到的问题:
Also keep in mind that setlocal/endlocal
actually limit scope of things changed inside so that they don't leak out. If you want to use count
after the endlocal
, you have to use a "trick" made possible by the very problem you're having:
endlocal && set count=%count%
让我们说 count
已在内部范围内变为7。因为整个命令在执行之前被解释,它有效地变成:
Let's say count
has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:
endlocal && set count=7
然后,当执行 关闭,返回 count
为它的原始值。但是,由于 count
到七的设置发生在外部范围,它有效地泄漏你需要的信息。
Then, when it's executed, the inner scope is closed off, returning count
to it's original value. But, since the setting of count
to seven happens in the outer scope, it's effectively leaking the information you need.
您可以将多个子命令串在一起,以泄漏所需的信息:
You can string together multiple sub-commands to leak as much information as you need:
endlocal && set count=%count% && set something_else=%something_else%
这篇关于使用Windows批处理脚本在FOR循环中计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!