windows 如何在嵌套循环批处理脚本中中断内循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4710552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to break inner loop in nested loop batch script
提问by Rock with IT
MY goal is to compare two files line by line and capture the changes. For that i am using two nested loops. I am stuck with braking the inner loop on some condition.
我的目标是逐行比较两个文件并捕获更改。为此,我使用了两个嵌套循环。在某些情况下,我坚持制动内循环。
I am using label outside the inner loop for break it, but not working. It goes to label and terminate outer loop also.
我在内循环外使用标签来打破它,但不起作用。它也去标记和终止外循环。
@ echo off
SETLOCAL EnableDelayedExpansion
for /F "skip=8 tokens=* delims=." %%a in (sample.txt) do (for /F "skip=8 tokens=* delims=." %%b in (test.txt) do (if %%a==%%b (goto :next) else ( echo %%a)
)
: Next
echo out of inner loop
)
Anyone can help....?
任何人都可以帮助......?
回答by jeb
A goto :label always breaks all loops.
goto :label 总是会中断所有循环。
But you can put your inner loop in a separated function, then it could work.
但是你可以把你的内部循环放在一个单独的函数中,然后它就可以工作了。
@echo off
SETLOCAL EnableDelayedExpansion
for /F "skip=8 tokens=* delims=." %%a in (sample.txt) do (
call :myInnerLoop "%%a"
)
echo out of inner loop
)
goto :eof
:myInnerLoop
for /F "skip=8 tokens=* delims=." %%b in (test.txt) do (
if "%~1"=="%%b" (
goto :next
) else (
echo %%a
)
:next
goto :eof
One remark, breaking of FOR /L loops does not work as expected, the for-loop always count to the end, but if you break it, the execution of the inner code is stopped, but it could be really slow.
一句话, FOR /L 循环的中断没有按预期工作,for 循环总是计数到最后,但是如果中断它,内部代码的执行就会停止,但它可能真的很慢。
@echo ON
FOR /L %%n IN (1,1,1000000) DO (
echo %%n - count
goto :break
)
:break
EDIT:
编辑:
Proof of concept
概念证明
@echo off
SETLOCAL EnableDelayedExpansion
for %%a in (a b c) DO (
echo Outer loop %%a
call :inner %%a
)
goto :eof
:inner
for %%b in (U V W X Y Z) DO (
if %%b==X (
echo break
goto :break
)
echo Inner loop Outer=%1 Inner=%%b
)
:break
goto :eof
Output
输出
Outer loop a
Inner loop Outer=a Inner=U
Inner loop Outer=a Inner=V
Inner loop Outer=a Inner=W
break
Outer loop b
Inner loop Outer=b Inner=U
Inner loop Outer=b Inner=V
Inner loop Outer=b Inner=W
break
Outer loop c
Inner loop Outer=c Inner=U
Inner loop Outer=c Inner=V
Inner loop Outer=c Inner=W
break
回答by user1037135
Even if the goto label is in the for loop, it also goes out the loop context. Such as
即使 goto 标签在 for 循环中,它也会离开循环上下文。如
@echo off
for %%d in (A B) do (
echo %%d
for %%f in ( 1 2 ) do (
goto loop
:loop
echo %%d %%f
)
)
This will print out A %d %f
这将打印出 A %d %f