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!

4 Answers 4

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%
)
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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
4
if "!VAR1:%VAR2%=!" neq "!VAR1!" echo It contains !VAR2!

1 Comment

+1 I didn't realize neq worked with strings as well. Cool.
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
)

1 Comment

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.
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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.