Batch file: Find if substring is in string (not in a file)

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Batch file: Find if substring is in string (not in a file)

Message par ForumBot »

Batch file: Find if substring is in string (not in a file)
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Batch file: Find if substring is in string (not in a file)

Message par ForumBot »

Yes, you can use substitutions and check against the original string:

```
if not x%str1:bcd=%==x%str1% echo It contains bcd

```

The `%str1:bcd=%` bit will replace a `bcd` in `str1` with an empty string, making it different from the original.

If the original didn't contain a `bcd` string in it, the modified version will be identical.

Testing with the following script will show it in action:

```
@setlocal enableextensions enabledelayedexpansion
@echo off
set str1=%1
if not x%str1:bcd=%==x%str1% echo It contains bcd
endlocal

```

And the results of various runs:

```
c:\testarea> testprog hello

c:\testarea> testprog abcdef
It contains bcd

c:\testarea> testprog bcd
It contains bcd

```

A couple of notes:

- The `if` statement is the meat of this solution, everything else is support stuff.

- The `x` before the two sides of the equality is to ensure that the string `bcd` works okay. It also protects against certain "improper" starting characters.
Répondre

Revenir à « Performance & Dépannage »