277

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?

1
  • 7
    BTW, it's usually either Windows and cmd or it's ms-dos. MSDOS hasn't been part of Windows for a long time.
    – paxdiablo
    Aug 10, 2011 at 4:56

13 Answers 13

357

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.
26
  • 9
    If you're looking on how to do string replacement in a FOR loop: stackoverflow.com/a/6310580/623622 Jul 22, 2012 at 8:44
  • 80
    This is great but I struggled to get this to work when the search value was not a constant (like bcd) but was instead a variable. After much time I finally figured it out. Assuming searchVal has been declared, "x!str1:%searchVal%=!"=="x%str1%" Jul 3, 2013 at 19:35
  • 10
    @Gary, since that wasn't one of the requirements of this question, you probably should have asked a different question, perhaps linking back to this one as a reference. There's no shortage of people willing to help out. In fact, you still shoud ask that question and answer it yourself (now that you've figured it out) so that it will be useful to future searchers. Self-answering is considered acceptable.
    – paxdiablo
    Jul 3, 2013 at 23:16
  • 16
    Very good solution, but you need to enclose in double quotes or it won't work with variables that have spaces in their values, e.g.: if not "x%str1:bcd=%" == "x%str1%" echo It contains bcd Jan 17, 2015 at 1:18
  • 7
    "'=str1 was unexpected at this time" Sep 4, 2015 at 12:37
120

You can pipe the source string to findstr and check the value of ERRORLEVEL to see if the pattern string was found. A value of zero indicates success and the pattern was found. Here is an example:

::
: Y.CMD - Test if pattern in string
: P1 - the pattern
: P2 - the string to check
::
@echo off

echo.%2 | findstr /C:"%1" 1>nul

if errorlevel 1 (
  echo. got one - pattern not found
) ELSE (
  echo. got zero - found pattern
)

When this is run in CMD.EXE, we get:

C:\DemoDev>y pqrs "abc def pqr 123"
 got one - pattern not found

C:\DemoDev>y pqr "abc def pqr 123" 
 got zero - found pattern
4
  • "FINDSTR: Argument missing after /C. got one - pattern not found" Sep 4, 2015 at 12:39
  • I was able to easily get this to work inside a for loop, too. I was unable to rework the accepted answer for a for loop (though, I didn't try very hard to see why it didn't work). Mar 4, 2021 at 18:08
  • This solution is very easy to read. I recommend checking this other answer for a few gotchas .
    – ASB
    Mar 31, 2021 at 13:17
  • ATTENTION! In some situation, findstr doesn't work correctly, for example, echo c:\_ | findstr /C:"\_" returns a match, but echo c:\_ | findstr /C:":\_" doesn't find a match, nor echo c:\_ | findstr /C:"c:\_". The workaround is to use find instead of findstr.
    – mo-han
    Oct 7, 2023 at 7:26
65

I usually do something like this:

Echo.%1 | findstr /C:"%2">nul && (
    REM TRUE
) || (
    REM FALSE
)

Example:

Echo.Hello world | findstr /C:"world">nul && (
    Echo.TRUE
) || (
    Echo.FALSE
)

Echo.Hello world | findstr /C:"World">nul && (Echo.TRUE) || (Echo.FALSE)

Output:

TRUE
FALSE

I don't know if this is the best way.

1
  • 1
    I needed to recursively find and compare file names. This was the only solution that worked for me as well! Super handy and very simple.
    – SirJames
    Nov 1, 2017 at 13:50
35

For compatibility and ease of use it's often better to use FIND to do this.

You must also consider if you would like to match case sensitively or case insensitively.

The method with 78 points (I believe I was referring to paxdiablo's post) will only match Case Sensitively, so you must put a separate check for every case variation for every possible iteration you may want to match.

( What a pain! At only 3 letters that means 9 different tests in order to accomplish the check! )

In addition, many times it is preferable to match command output, a variable in a loop, or the value of a pointer variable in your batch/CMD which is not as straight forward.

For these reasons this is a preferable alternative methodology:

Use: Find [/I] [/V] "Characters to Match"

[/I] (case Insensitive) [/V] (Must NOT contain the characters)

As Single Line:

ECHO.%Variable% | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )

Multi-line:

ECHO.%Variable%| FIND /I "ABC">Nul && ( 
  Echo.Found "ABC"
) || (
  Echo.Did not find "ABC"
)

As mentioned this is great for things which are not in variables which allow string substitution as well:

FOR %A IN (
  "Some long string with Spaces does not contain the expected string"
  oihu AljB
  lojkAbCk
  Something_Else
 "Going to evaluate this entire string for ABC as well!"
) DO (
  ECHO.%~A| FIND /I "ABC">Nul && (
    Echo.Found "ABC" in "%A"
  ) || ( Echo.Did not find "ABC" )
)

Output From a command:

    NLTest | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )

As you can see this is the superior way to handle the check for multiple reasons.
5
  • for case sensitivity issue, you can use setlocal EnableExtensions then IF /I to do case insensitive comparisons.
    – cychoi
    Oct 5, 2014 at 11:12
  • 1
    That's not really an option because you would still need to isolate the characters for an "IF" Comparison. IF won't match in "Like" Terms as the OP and particular solutions I replied to are looking for., Aug 12, 2016 at 1:05
  • 3
    Hi Ben, Please don't refer to other answers by the number of points they have. That's likely to change. Please update your answer referring to the other answer by that answer's author name, or by a brief phrase describing the technique used in that answer. Aug 1, 2017 at 16:00
  • Hi Phone Tagger, that would have been a helpful comment three years ago when I wrote the original post, however as you mention the points values have all changed. I no longer remember which post I was referring to, and I wouldn't be referring to them by points values today. Thanks anyway. Aug 1, 2017 at 17:39
  • I looked around and I believe I was referring to paxdiablo, so I've amended the text to show that. Aug 1, 2017 at 17:55
12

If you are detecting for presence, here's the easiest solution:

SET STRING=F00BAH
SET SUBSTRING=F00
ECHO %STRING% | FINDSTR /C:"%SUBSTRING%" >nul & IF ERRORLEVEL 1 (ECHO CASE TRUE) else (ECHO CASE FALSE)

This works great for dropping the output of windows commands into a boolean variable. Just replace the echo with the command you want to run. You can also string Findstr's together to further qualify a statement using pipes. E.G. for Service Control (SC.exe)

SC QUERY WUAUSERV | findstr /C:"STATE" | FINDSTR /C:"RUNNING" & IF ERRORLEVEL 1 (ECHO case True) else (ECHO CASE FALSE)

That one evaluates the output of SC Query for windows update services which comes out as a multiline text, finds the line containing "state" then finds if the word "running" occurs on that line, and sets the errorlevel accordingly.

2
  • 8
    You have your IF Statement Backward.. Looking at the original with abcdefg and you flip-flop your logic. It works. The way you have it, it does not. SET STRING=abcdefgh SET SUBSTRING=bcd ECHO %STRING% | FINDSTR /C:"%SUBSTRING%" >nul & IF ERRORLEVEL 1 (ECHO CASE FALSE) else (ECHO CASE TRUE)
    – Leptonator
    Feb 10, 2015 at 21:21
  • 2
    A +1 is due even though @Leptonator is correct with the inverted logic. This is a simple and easy-to-use solution. Nov 21, 2015 at 15:11
8

To find a text in the Var, Example:

var_text="demo string test"
Echo.%var_text% | findstr /C:"test">nul && (
    echo "found test" 
    ) || Echo.%var_text% | findstr /C:"String">nul && (
             echo "found String with S uppercase letter" 
    ) || (
             echo "Not Found " 
    )

LEGEND:

  1. & Execute_that AND execute_this
  2. || Ex: Execute_that IF_FAIL execute this
  3. && Ex: Execute_that IF_SUCCESSFUL execute this
  4. >nul no echo result of command
  5. findstr
  6. /C: Use string as a literal search string
1
6

I'm probably coming a bit too late with this answer, but the accepted answer only works for checking whether a "hard-coded string" is a part of the search string.

For dynamic search, you would have to do this:

SET searchString=abcd1234
SET key=cd123

CALL SET keyRemoved=%%searchString:%key%=%%

IF NOT "x%keyRemoved%"=="x%searchString%" (
    ECHO Contains.
)

Note: You can take the two variables as arguments.

6

Best approach for me would be this:

call :findInString "HelloWorld" "World"

:findInString
ECHO.%1 | FIND /I %2>Nul && ( 
  Echo.Found
) || (
  Echo.Not found
)
4
ECHO %String%| FINDSTR /C:"%Substring%" && (Instructions)
1
  • Thanks a lot, exactly what I was looking for. Explanations are missing, but other comments were helping aswell. Having to check if a substring is not in a string goes as ECHO %string% | FINDSTR %substring% || (when_false) . The /C: modifier isn't mandatory, and beware that " around the substring may be looked after. Mar 1 at 13:19
1

Better answer was here:

set "i=hello " world"
set i|find """" >nul && echo contains || echo not_contains
1
  • In the question you link using SET is solving a specific and unique need, so there it is important to mention "SET". However, it does not appear to add anything to the current discussion, as the method of piping a command to the FIND command and testing the result is already provided Jun 4, 2019 at 17:52
1

The solutions that search a file for a substring can also search a string, eg. find or findstr.
In your case, the easy solution would be to pipe a string into the command instead of supplying a filename eg.

case-sensitive string:
echo "abcdefg" | find "bcd"

ignore case of string:
echo "abcdefg" | find /I "bcd"

IF no match found, you will get a blank line response on CMD and %ERRORLEVEL% set to 1

1

Built on @user839791's answer, but I've added a few more things.

@echo off
rem --Set variable below--
set var=condition

rem --Uncomment below line to display contents of variable--
::echo The variable is %var%

rem --Change condition to desired string below--
ECHO.%var%| FIND /I "condition">Nul && (  
  rem --Occurs if the string is found--
  Echo.Variable is "condition"
  color C
  pause
) || (
  rem --Occurs if the string isn't found--
  Echo.Variable is not "condition"
  color A
  pause
)
1

Yes, We can find the subString in the String:

echo.%data% | FINDSTR /I "POS">Nul && (SET var=POS) || (SET noVar="variable not found")

echo.%data% | FINDSTR /I "TD1">Nul && (SET var=TD1) || (SET noVar="variable not found")

GOTO %var%

:POS   
echo processes inside POS  
GOTO END

:TD1   
echo processes inside TD1

:END

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.