'DOS: find a string, if found then run another script

I want to find a string in a file using DOS:

For example

find "string" status.txt

And when it is found, I want to run a batch file.

What is the best way to do this?



Solution 1:[1]

It's been awhile since I've done anything with batch files but I think that the following works:

find /c "string" file
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done

This is really a proof of concept; clean up as it suits your needs. The key is that find returns an errorlevel of 1 if string is not in file. We branch to notfound in this case otherwise we handle the found case.

Solution 2:[2]

C:\test>find /c "string" file | find ": 0" 1>nul && echo "execute command here"

Solution 3:[3]

We have two commands, first is "condition_command", second is "result_command". If we need run "result_command" when "condition_command" is successful (errorlevel=0):

condition_command && result_command

If we need run "result_command" when "condition_command" is fail:

condition_command || result_command

Therefore for run "some_command" in case when we have "string" in the file "status.txt":

find "string" status.txt 1>nul && some_command

in case when we have not "string" in the file "status.txt":

find "string" status.txt 1>nul || some_command

Solution 4:[4]

As the answer is marked correct then it's a Windows Dos prompt script and this will work too:

find "string" status.txt >nul && call "my batch file.bat"

Solution 5:[5]

That's more straightforward:

find /c "string" file
if %errorlevel% not equ 1 goto something

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Spikolynn
Solution 3 snv.dev
Solution 4 foxidrive
Solution 5 Marco Gamer34