Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a variable to part of another variable in batch

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?

like image 279
user2344996 Avatar asked Dec 02 '25 21:12

user2344996


1 Answers

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
)
like image 197
dbenham Avatar answered Dec 05 '25 14:12

dbenham



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!