Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace a string variable within a string variable in my cmd batch file?

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!

like image 374
Andrew Avatar asked Jun 15 '26 10:06

Andrew


2 Answers

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%
)
like image 178
rojo Avatar answered Jun 18 '26 00:06

rojo


if "!VAR1:%VAR2%=!" neq "!VAR1!" echo It contains !VAR2!
like image 32
Aacini Avatar answered Jun 18 '26 01:06

Aacini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!