Skip to main content

How to Check if a String Contains a Substring in Batch Script

A fundamental operation in any programming language is checking if a string of text contains a smaller piece of text (a substring). This is essential for parsing log files to find error messages, validating user input, or checking filenames for specific keywords. While Windows Batch doesn't have a simple, built-in contains() function, it provides a couple of powerful methods to achieve this.

This guide will teach you the two primary techniques for finding a substring. We'll cover the classic, "pure-batch" method using string substitution, which is fast and self-contained, and the alternative method using the FINDSTR command, which offers powerful features like case-insensitivity.

The Core Method: String Substitution Trick

This is the most common and efficient "native" batch method. It works by replacing the substring you're looking for with an empty string. If the original string changes as a result, it means the substring must have been present.

The Logic: IF NOT "!MyString!"=="!MyString:Sub=!" ECHO String contains Sub

This relies on Delayed Expansion, which must be enabled.

An Alternative Method: Using FINDSTR

The FINDSTR command is a powerful utility for searching for text. You can ECHO your main string and pipe it to FINDSTR, which will then search for the substring. FINDSTR sets the %ERRORLEVEL% variable to 0 if it finds a match, and 1 if it does not.

The Syntax:

ECHO "My String" | FINDSTR /I "Substring" > NUL

IF %ERRORLEVEL% EQU 0 (ECHO Found it)

This method's key advantage is the /I switch, which makes the search case-insensitive.

Basic Example: A Simple "Contains" Check

Let's check if a log line contains the word "ERROR". We'll use the recommended string substitution method.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET "LogLine=INFO: Process completed successfully."
SET "SearchTerm=ERROR"

ECHO Log Line: "!LogLine!"
ECHO Searching for: "!SearchTerm!"
ECHO.

REM Perform the check
IF NOT "!LogLine!"=="!LogLine:%SearchTerm%=!" (
ECHO [RESULT] The log line contains the search term.
) ELSE (
ECHO [RESULT] The log line does not contain the search term.
)

Output (for the first LogLine)

Log Line: "INFO: Process completed successfully."
Searching for: "ERROR"

[RESULT] The log line does not contain the search term.

If you change LogLine to SET "LogLine=ERROR: Failed to connect to database.", the output becomes:

[RESULT] The log line contains the search term.

How the String Substitution Trick Works

The magic is in the syntax !LogLine:%SearchTerm%=!.

  • LogLine: The name of the variable holding the main string.
  • :: The separator that indicates a substitution is about to happen.
  • %SearchTerm%: The substring to find.
  • =: The assignment operator.
  • (nothing): The replacement string. In this case, we are replacing the search term with nothing.

So, if LogLine is ERROR: Failure, then !LogLine:ERROR=! evaluates to : Failure. The IF statement becomes IF NOT "ERROR: Failure"==": Failure", which is true, so the "contains" logic is triggered.

The string substitution method is always case-sensitive. It will not find "error" if you are searching for "ERROR". For case-insensitive searches, FINDSTR is the superior tool.

@ECHO OFF
SET "LogLine=Warning: an error occurred."
SET "SearchTerm=ERROR"

ECHO "%LogLine%" | FINDSTR /I /C:"%SearchTerm%" > NUL

IF %ERRORLEVEL% EQU 0 (
ECHO Found a case-insensitive match.
) ELSE (
ECHO No match found.
)
  • /I: Makes the search Insensitive to case.
  • /C:"string": Treats the search term as a literal string.

Output:

Found a case-insensitive match.

Common Pitfalls and How to Solve Them

Problem: Delayed Expansion is Not Enabled

The string substitution method will fail completely if you do not enable delayed expansion. Using standard % variables will not work.

In case of error, without SETLOCAL ENABLEDELAYEDEXPANSION, the IF statement is parsed only once, and the substitution will not happen as expected.

Solution: Always Use SETLOCAL ENABLEDELAYEDEXPANSION

This should be at the top of any script that uses the !variable:sub=replace! syntax.

Problem: Handling Special Characters

Characters like &, |, >, <, and " can cause issues, especially with the FINDSTR method, as the ECHO command might interpret them before they are piped.

Solution: Careful Quoting and String Substitution

The string substitution method (!var:sub=!) is generally safer with special characters because it happens internally without needing ECHO. When using FINDSTR, ensuring your search string and the string being searched are well-quoted can help, but it can still be tricky. For most cases, the substitution method is more robust.

Practical Example: Filtering Files in a Loop

This script loops through all text files in a directory and renames any file that contains the word "DRAFT" in its filename.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

ECHO --- Renaming DRAFT files ---
ECHO.

FOR %%F IN (*.txt) DO (
SET "filename=%%F"

REM Check if the filename contains "DRAFT"
IF NOT "!filename!"=="!filename:DRAFT=!" (
ECHO Found draft file: "!filename!"

REM Create the new name
SET "newname=!filename:DRAFT=FINAL!"

ECHO Renaming to: "!newname!"
REN "!filename!" "!newname!"
ECHO.
)
)

ECHO --- Done ---
ENDLOCAL

Conclusion

Checking for a substring is a fundamental scripting task that can be handled effectively in batch with the right technique.

  • For most case-sensitive checks, the string substitution method (!VAR:sub=!) is the best choice. It's fast, self-contained, and generally safer with special characters. Remember to enable delayed expansion.
  • For case-insensitive searches or when you need the power of regular expressions, the FINDSTR method is the superior tool.

By choosing the right method for your needs, you can easily build powerful and intelligent logic into your batch scripts.