3

I want to match a variable to part of the contents of another variable in batch. Here is some pseudo code for what I want to do.

set h= Hello-World
set f= This is a Hello-World test

if %h% matches any string of text in %f% goto done
:done
echo it matched

Does anybody know how I could accomplish this?

user2344996
  • 1,643
  • 2
  • 12
  • 8
  • 1
    Caution - since it's no explicitly mentioned in responses - spaces are significant in `SET` string statements, so the values you have set into the variables INCLUDE the leading space (and any trailing spaces.) Confusingly, this also applies to the variable name (set h =something` would set "`h `" not "`h`". Using the `set "var=string"` syntax overcomes the trailing-space problem. – Magoo Sep 28 '13 at 09:40

3 Answers3

2

Based off of this answer here, you can use the FINDSTR command to compare the strings using the /C switch (modified from the linked answer so you don't have to have a separate batch file for comparing the strings):

@ECHO OFF

set h=Hello-World
set f=This is a Hello-World test

ECHO Looking for %h% ...
ECHO ... in %f%
ECHO.

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

if errorlevel 1 (
  ECHO String "%h%" NOT found in string "%f%"!
) ELSE (
  ECHO String "%h%" found in string "%f%"!
)

ECHO.    

PAUSE
Community
  • 1
  • 1
LittleBobbyTables - Au Revoir
  • 32,008
  • 25
  • 109
  • 114
2

If the following conditions are met:

  • The search is case insensitive
  • The search string does not contain =
  • The search string does not contain !

then you can use:

@echo off
setlocal enableDelayedExpansion
set h=Hello-World
set f=This is a Hello-World test
if "!f:*%h%=!" neq "!f!" (
  echo it matched
) else (
  echo it did not match
)

The * preceding the search term is only needed to allow the search term to start with *.

There may be a few other scenarios involving quotes and special characters where the above can fail. I believe the following should take care of such problems, but the original constraints still apply:

@echo off
setlocal enableDelayedExpansion
set h=Hello-World
set f=This is a Hello-World test
for /f delims^=^ eol^= %%S in ("!h!") do if "!f:*%%S=!" neq "!f!" (
  echo it matched
) else (
  echo it did not match
)
dbenham
  • 127,446
  • 28
  • 251
  • 390
1

Here's another way:

@echo off
set "h=Hello-World"
set "f=This is a Hello-World test"
call set "a=%%f:%h%=%%"
if not "%a%"=="%f%" goto :done
pause
exit /b
:done
echo it matched
pause
foxidrive
  • 40,353
  • 10
  • 53
  • 68