使用 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%
)
推荐答案
它不起作用,因为整个 for
循环(来自 for
到最后一个右括号,包括它们之间的命令)在遇到它时被评估,在它开始执行之前.
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%
被替换为它的值 1
.
In other words, %count%
is replaced with its value 1
before running the loop.
您需要的是:
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
设置为 7 发生在外部作用域中,因此实际上泄漏了您需要的信息.
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屋!