FOR loop : make it stop itself

Microsoft Windows
Post Reply
length
Posts: 1
Joined: 2023-Dec-01, 9:28 pm

FOR loop : make it stop itself

Post by length »

FOR /f "tokens=4,5" %i in (file.txt) DO if %j == sometext echo %i %j
outputs desired content, but I want processing to quit upon first occurrence,
and not by exiting the console.
OJBakker
Posts: 13
Joined: 2021-Jul-29, 7:06 am

Re: FOR loop : make it stop itself

Post by OJBakker »

This will echo just the first result found.
It will not stop processing the entire file.

Code: Select all

set "found=" & FOR /f "tokens=4,5" %i in (file.txt) DO @if not defined found if "%j" == "sometext" echo %i %j & set "found=1"
Rekrul
Posts: 51
Joined: 2021-Aug-15, 11:29 pm

Re: FOR loop : make it stop itself

Post by Rekrul »

length wrote: 2023-Dec-01, 9:53 pm FOR /f "tokens=4,5" %i in (file.txt) DO if %j == sometext echo %i %j
outputs desired content, but I want processing to quit upon first occurrence,
and not by exiting the console.
You can do it inside a script;

Code: Select all

@echo off
FOR /f "tokens=4,5" %%i in (file.txt) DO (
if "%%j" == "sometext" echo %%i %%j
if "%%j" == "sometext" goto Label
)
goto:eof

:Label
echo Match found. Processing stopped.
The IF/GOTO breaks the loop when a match is found, by jumping outside the loop to "Label". Currently, all it does is print a message and then the script ends, but you can have it do whatever you want. If you call this script from an open console window, it will remain open when it ends. The "goto:eof" is necessary in case the file doesn't contain a match, it will end there and return to the console rather than executing the echo statement.

It can be made a little more flexible with;

Code: Select all

@echo off
FOR /f "tokens=4,5" %%i in (%1) DO (
if "%%j" == "%2" echo %%i %%j
if "%%j" == "%2" goto Label
)
goto:eof

:Label
echo Match found. Processing stopped.
Save this with a unique name, like file-search,bat, then call it with the name of the file to be searched, and the text to search for, like this;

file-search.bat file.txt sometext

I'm sure there's some reason why doing this is very, very bad, but it works in all my tests and as long as you aren't doing it dozens or hundreds of times, it shouldn't cause any major problems.
Post Reply