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

Updated: 04/26/2017 by Computer Hope
Batch file

Using the findstr command allows you to search for text within any plaintext file. Using this command within a batch file allows 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. It prints any files found containing this string into the results.txt file. Also, this batch file has an else statement that will print if no matches were found.


When doing the "else," it *must* follow the close parenthesis. It must be ") else (" or 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