2

I want to see if a string contains another string where both strings are variables. Basically it is that same as this thread but with two variables. Taking that solution and applying it to my situation with !VAR1! and !VAR2! (these variables are declared within the FOR loop) I tried:

if not x!VAR1:!VAR2!=!==x!VAR1! ECHO It contains !VAR2!

Unfortunately it doesn't work. Any help would be greatly appreciated. I have also declared SETLOCAL EnableDelayedExpansion so I can access the variables.

Any help would be greatly appreciated!

Thanks!

Community
  • 1
  • 1
Andrew
  • 293
  • 6
  • 14

4 Answers4

4

When I'm checking whether a string exists within another string, I like to use a for loop rather than if.

for /f "delims=" %%I in ('echo !VAR1! ^| findstr /i /c:"!VAR2!"') do (
    echo !VAR1! contains !VAR2!
)

This has the added benefit of case-insensitive matches.


If you prefer keeping the if statement, then try an intermediate variable to reduce confusion.

set vt=!VAR1:%VAR2%=!
if x%vt%==x%VAR1% (
    echo %VAR1% remained the same after removing %VAR2%.  %VAR1% did not contain %VAR2%
)
rojo
  • 24,000
  • 5
  • 55
  • 101
  • Variable expansion search and replace is always case insensitive. FINDSTR gives you the option of case sensitive or insensitive search. I prefer the IF method if doing case insensitive search - it is much faster. – dbenham Feb 21 '13 at 04:15
  • No need for FOR /F when using FINDSTR. Also, your current FOR /F may print multiple times if `!VAR1!` contains linefeeds. If using FOR /F, then better to do it like [Patrick's answer](http://stackoverflow.com/a/14985463/1012053) – dbenham Feb 21 '13 at 12:03
4
if "!VAR1:%VAR2%=!" neq "!VAR1!" echo It contains !VAR2!
Aacini
  • 65,180
  • 12
  • 72
  • 108
3

This is the simplest way in my opinion.

echo %VAR1% | find /i "%VAR2%" >nul && echo %VAR2% was found!

Replace && with || for if not found.

Patrick Meinecke
  • 3,963
  • 2
  • 18
  • 26
3

As Aacini and rojo have shown, you must use a different expansion for the two variables, normal inside, and delayed outside.

But perhaps you are running the IF within the same code block that sets the variable. Now you can't use normal expansion. The solution is to transfer the inner variable to a FOR variable.

(
  :: Some code that sets the value of var2 
  ::
  for /f "delims=" %%A in ("!var2!") do if "!var1:%%A=!" neq "!var1!" echo It contains %%A
)
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • Thank you for your input. This solution worked for me since the IF is indeed running within the same code block that sets the variable. – Andrew Feb 21 '13 at 14:18