[batch-file] 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?

This question is related to batch-file dos

The answer is


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

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.


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

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"