How to see if a string contains a substring using batch

42,798

Solution 1

echo %%a|find "substring" >nul
if errorlevel 1 (echo notfound) else (echo found)

Batch is sensitive to spaces in a SET statement. SET FLAG = N sets a variable named "FLAGSpace" to a value of "SpaceN"

The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a can safely be used "quoteless".

Solution 2

As an alternative to find, you can use string substitution, like this:

@echo off
setlocal EnableDelayedExpansion
set "substring=#"
for /f "delims=," %%a in (Text.txt) do (
    set "string=%%a"
    if "!string:%substring%=!"=="!string!" (
        rem string with substring removed equals the original string,
        rem so it does not contain substring; therefore, output it:
        echo(!string!
    )
)
endlocal

This approach uses delayed environment variable expansion. Type setlocal /? in command prompt to find out how to enable it, and set /? to see how it works (read variables like !string! instead of %string%) and what it means. set /? also describes the string substitution syntax.

Solution 3

I had to create a function:

Use it as:

SearchText = "Why does the purple cow jump over the moon?"
SearchTerm = "Purple"
CALL:checkIfStringCotainsText "%SearchText%" "%SearchTerm%" RESULT
IF %RESULT%==true(
    ECHO Text Found!
) ELSE (
    ECHO Text NOT Found.
)

Remember it is not case sensitive by default. Add the word true to the end of the Call if you would like to be case sensitive such as:

SearchText = "Why does the purple cow jump over the moon?"
SearchTerm = "Purple"
CALL:checkIfStringCotainsText "%SearchText%" "%SearchTerm%" RESULT true
REM # Returns false because Purple is capitalized

And these Functions to the bottom of your Batch File.

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B

:checkIfStringCotainsText 
@REM # CHECKS IF A STRING CONTAINS A SUBSTRING
@REM # Returns the %3 as either set to true or false
@REM # Not case sensetive by defualt. But can be set to case sensetive buying adding true as the fourth paramater
@REM # For example: CALL:checkIfStringCotainsText "Whats up SLY Fox?"   "fox"          RESULT              true
@REM #                                                 SearchText     SearchTerm 
   true-or-false    CaseSensetive?
@Rem # Will check if "Whats up SLY Fox?"" contains the text "fox"
@REM # Then check the result with: if %RESULT%==true (Echo Text Found) Else (Text Not Found)
@REM # Remember do not add %RESULT% use only RESULT .Do not add % around RESULT when calling the function.
@REM # Only add % around RESULT when checking the result.
@REM # Make sure to add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your Batch File! This is important!
@REM # Make sure you use quotes around SearchText and SearchTerm. For example "SearchText" not SearchText.
@REM # This is because if there is a space inside the SearchText, each space will make it look like a new parameter



SET SearchString=%~1
SET SearchTerm=%~2
@REM #Check if Case Senseitive
IF [%~4]==[true] (
    @REM if %~4 is not set to anything, treat it as the default as false
    @REM - Do nothing as FindStr is normally case sensetive
) ELSE (
    @REM Change both the text and search-term both to lowercase.
    CALL:LCase SearchString SearchString
    CALL:LCase SearchTerm SearchTerm

)
@set containsText=false
@echo DEBUG: Searching for ^|%~2^| inside ^|%~1^|
@echo "!SearchString!" | find "!SearchTerm!" > nul && if errorlevel 0 (set containsText=true)
SET %3=!containsText!
@GOTO:EOF


:LCase
:UCase
@REM Converts Text to Upper or Lower Case
@REM Brad Thone robvanderwoudeDOTcom
:: Converts to upper/lower case variable contents
:: Syntax: CALL :UCase _VAR1 _VAR2
:: Syntax: CALL :LCase _VAR1 _VAR2
:: _VAR1 = Variable NAME whose VALUE is to be converted to upper/lower case
:: _VAR2 = NAME of variable to hold the converted value
:: Note: Use variable NAMES in the CALL, not values (pass "by reference")
SET _UCase=A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
SET _LCase=a b c d e f g h i j k l m n o p q r s t u v w x y z
SET _Lib_UCase_Tmp=!%1!
IF /I "%0"==":UCase" SET _Abet=%_UCase%
IF /I "%0"==":LCase" SET _Abet=%_LCase%
FOR %%Z IN (%_Abet%) DO SET _Lib_UCase_Tmp=!_Lib_UCase_Tmp:%%Z=%%Z!
SET %2=%_Lib_UCase_Tmp%
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.
Share:
42,798
FyreeW
Author by

FyreeW

Updated on August 08, 2020

Comments

  • FyreeW
    FyreeW almost 4 years

    Currently trying to see if a string, in this case the current line of a text file, contains a substring #. I am new to batch, so I am not sure exactly how I would do something like this. Here is the code set substring = #

    for /f "delims=," %%a in (Text.txt) do (
        set string = %%a
    
        //check substring method        
    
        echo %string%
    
    )
    
  • FyreeW
    FyreeW over 8 years
    I do not want to print out %%a|find "substring" >nul if errorlevel 1 (echo notfound) else (echo found), just only print the string if it does not contain #
  • Magoo
    Magoo over 8 years
    Sorry- my crystal ball must be on the blink again. Replace notfound with %%a and lose the else clause. These commands must be within the for loop.
  • FyreeW
    FyreeW over 8 years
    Alright, it works now. Is there a way to do it without it printing out the code?
  • Magoo
    Magoo over 8 years
    First line of a batch file is normally @echo off which suppresses the code display.
  • aschipfl
    aschipfl over 8 years
    See my edit: I accidently did not use delayed expansion for string although I described it...
  • Behrouz.M
    Behrouz.M about 5 years
    @Magoo u should use findstr instead of find
  • Magoo
    Magoo about 5 years
    @raypixar: Interesting assertion. Do you have a reason for advocating findstr over find?
  • Behrouz.M
    Behrouz.M about 5 years
    @Magoo i've tested your code with find it did not work. it only works with findstr
  • Magoo
    Magoo about 5 years
    @raypixar: Sadly, you've not provided sufficient data to analyse the problem. What string did you attempt to find within what textstring for instance - and what was the result? I Strongly suspect that you have installed Cygwin or some other *nix emulator, which overrides Windows' find utility with the nixy locate-a-file function. Under those circumstances, any Windows batch file which expects Windows' find will fail unless you explicitly specify the name of the find executable (Usually %windir%\System32\find.exe for 32-bit systems)
  • Behrouz.M
    Behrouz.M about 5 years
    @magoo sorry my bad, u are searching in a file ? I was searching in string