Home > Software engineering >  How to find with a batch file a substring in string inside a loop?
How to find with a batch file a substring in string inside a loop?

Time:05-27

This is the code used by me:

setlocal enabledelayedexpansion
set argCount=0
for %%x in (%*) do (
   set /A argCount =1
   set "argVec[!argCount!]=%%~x"
)
echo Number of processed arguments: %argCount%
set str1=hello
for /L %%i in (1,1,%argCount%) do (
    set "str2=!argVec[%%i]!"
    If NOT "!str1!"=="!str1:!str2!=!" set COND=1
    echo !COND!
)

This code counts the parameters passed to the batch file and assign them to environment variables. The environment variable COND should be defined with 1 only if a parameter string contains the string hello.

The problem is in this line:

If NOT "!str1!"=="!str1:!str2!=!" set COND=1

Variable COND is always defined with 1.

Any ideas how can I solve it?

PS: str2 is defined with the current parameter (argument) to check for hello.

CodePudding user response:

@ECHO OFF
setlocal enabledelayedexpansion
set argCount=0
set "str1=hello"
SET /a cond=0
for %%x in (%*) do (
 set /A argCount =1
 set "argVec[!argCount!]=%%~x"
 IF NOT "%str1%"=="!str1:%%~x=!" SET /a cond=argcount
 ECHO !cond!
)
echo Number of processed arguments: %argCount%
GOTO :EOF

would show the argument number in which the substring was found as cond and cond would be set to the last of these finds or 0 if none was found

  • Related