Searching for a string of text in an MS-DOS batch file

Batch fileUsing the findstr command allows you to search for text within any plaintext file. Using this command within a batch file allow you to search for text and create events off the results found. Below are some examples.

Basic search

In the example below, this basic batch file would search through the hope.txt file for the string computerhope and if found echo back to the screen There is hope!.

@echo off
findstr /m "computerhope" hope.txt
if %errorlevel%==0 (
echo There is hope!
)

Log results and wildcards

In the example below, this batch file searches for computerhope in any txt file in the current directory using the wildcards *.txt then prints the files containing this string into the results.txt file. In addition, this batch file also has an else statement that will print if no matches were found. Note: When doing the else it *must* follow the close parenthesis, so it must be ") else (" otherwise you'll get the 'else' is not recognized as an internal or external command, operable program or batch file." error.

@echo off
findstr /m "computerhope" *.txt > results.txt
if %errorlevel%==0 (
echo Found! logged files into results.txt
) else (
echo No matches found
)

Additional information