SRel
SRel

Reputation: 423

Exit a loop when a value was found

I have a file with several lines:

"pathToFile=%~dp0PBreport\cpy\Install\"

More, I have a list of strings with different search values:

"searchValue=abc,there,rtz"

My aim is to search each line of the file for the occurence of a search value and then execute some code. However, if maybe the first element in my list of search values is found it is not necesseray to check the other values. I do the whole thing with a nested foor loop, however when I implement something like GOTO the outer loop do not continue. Is tehre some mistake using GOTO inside a loop? Or is there a better way to exit and skipp all other checkings if one was already found? The complete Code work without problem without the GOTOstatement.

FOR /f "tokens=1 delims=" %%G in (%pathToFile%) do (
  set "dataRow=%%~G"
  FOR %%I in (%searchValue%) do ( 
      IF not "!dataRow:%%I=!"=="!dataRow!" (
      ### some Code here ###
      GOTO endIfCases
      )
  )
  ###some similiar blocks like the one above which can also be ignored if one match was found beforehand###

  :endIfCases
  ### some Code which needs to be excecuted at the end of each loop from the outer FOR###
)

Upvotes: 0

Views: 255

Answers (2)

Aacini
Aacini

Reputation: 67216

This solution is simple and efficient:

FOR /f "tokens=1 delims=" %%G in (%pathToFile%) do (
  set "dataRow=%%~G"
  set "break="
  FOR %%I in (%searchValue%) do if not defined break ( 
      IF not "!dataRow:%%I=!"=="!dataRow!" (
      ### some Code here ###
      set "break=1"
      )
  )
  ###some similiar blocks like the one above which can also be ignored if one match was found beforehand###

  ### some Code which needs to be excecuted at the end of each loop from the outer FOR###
)

Upvotes: 2

RGuggisberg
RGuggisberg

Reputation: 4750

Can you arrange your code something like this (passing parameters to subroutine as needed):

FOR /f "tokens=1 delims=" %%G in (%pathToFile%) do (
   CALL :YourSubr "Parm1" "Parm2"
     ### some Code which needs to be excecuted at the end of each loop from the outer FOR###
)
GOTO :eof

:YourSubr
REM 1=???
REM 2=???
set "dataRow=%%~G"
FOR %%I in (%searchValue%) do ( 
   IF not "!dataRow:%%I=!"=="!dataRow!" (
   ### some Code here ### using passed parameters
   )
)

I see you are using delayed expansion but your code does not show the SETLOCAL... so be careful with where your ENDLOCAL is placed.

Upvotes: 0

Related Questions