Search code examples
windowsbatch-filecmdsubstring

Batch file: Find if substring is in string (not in a file)


In a batch file, I have a string abcdefg. I want to check if bcd is in the string.

Unfortunately it seems all of the solutions I'm finding search a file for a substring, not a string for a substring.

Is there an easy solution for this?


Solution

  • Yes, you can use substitutions and check against the original string:

    if not x%str1:bcd=%==x%str1% echo It contains bcd
    

    The %str1:bcd=% bit will replace a bcd in str1 with an empty string, making it different from the original.

    If the original didn't contain a bcd string in it, the modified version will be identical.

    Testing with the following script will show it in action:

    @setlocal enableextensions enabledelayedexpansion
    @echo off
    set str1=%1
    if not x%str1:bcd=%==x%str1% echo It contains bcd
    endlocal
    

    And the results of various runs:

    c:\testarea> testprog hello
    
    c:\testarea> testprog abcdef
    It contains bcd
    
    c:\testarea> testprog bcd
    It contains bcd
    

    A couple of notes:

    • The if statement is the meat of this solution, everything else is support stuff.
    • The x before the two sides of the equality is to ensure that the string bcd works okay. It also protects against certain "improper" starting characters.