How to check if text file contain certain text in batch?

Here is an alternative approach that also works. The code uses the findstr commmand to look inside the text file and find the specific string... returning an error level of 0 (if found) or an error level of 1 (if the string wasn't found).

findstr /m "Findme" Log.txt >Nul
if %errorlevel%==0 (
echo "Findme" was found within the Log.txt file!
)

if %errorlevel%==1 (
echo "Findme" wasn't found within the Log.txt file!
)
pause

You should use either FIND or FINDSTR. Type HELP FIND and HELP FINDSTR from a command prompt to get documentation. FIND is very simple and reliable. FINDSTR is much more powerful, but also tempermental. See What are the undocumented features and limitations of the Windows FINDSTR command? for more info.

You don't care about the output of either command, so you can redirect output to nul.

Both commands set ERRORLEVEL to 0 if the string is found, and 1 if the string is not found. You can use the && and || operators to conditionally execute code depending on whether the string was found.

>nul find "Hello World" log.txt && (
  echo "Hello World" was found.
) || (
  echo "Hello World" was NOT found.
)

>nul findstr /c:"Hello World" log.txt && (
  echo "Hello World" was found.
) || (
  echo "Hello World" was NOT found.
)

You could also test ERRORLEVEL in an IF statement, but I prefer the syntax above.

Tags:

Batch File