Saturday, June 12, 2010

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

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

Question:

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

Answer:

Using the findstr command will enable you to search for text within any plaintext file. Using this command within a batch file will 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:

· See our findstr command page for additional information about this command and the complete syntax.


No comments:

Post a Comment