Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

windows - How to break inner loop in nested loop batch script

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....?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A goto :label always breaks all loops.

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.

@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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...