How to get position of the sub string in string in batch How to get position of the sub string in string in batch windows windows

How to get position of the sub string in string in batch


@echo OFFSETLOCALSet "str1=This is Test string"Set "sstr=Test"SET stemp=%str1%&SET pos=0:loopSET /a pos+=1echo %stemp%|FINDSTR /b /c:"%sstr%" >NULIF ERRORLEVEL 1 (SET stemp=%stemp:~1%IF DEFINED stemp GOTO loopSET pos=0)ECHO Pos of "%sstr%" IN "%str1%" = %pos%

(This returns "9", counting the first position as "1". The definition is in the mind of the user...)


And an additional alternative:

@echo off &setlocal enabledelayedexpansionSet "str1=This is Test string"Set "sstr=Test"set /a position=0Set "sst0=!str1:*%sstr%=!"if "%sst0%"=="%str1%" echo "%sstr%" not found in "%str1%"&goto :eofSet "sst1=!str1:%sstr%%sst0%=!"if "%sst1%" neq "" for /l %%i in (0,1,8189) do if "!sst1:~%%i,1!" neq "" set /a position+=1echo.Position of %sstr% is %position%endlocal

If %str1% contains more than one %sstr%, the code will find the first position.


Try this:

@echo off &setlocal enabledelayedexpansionSet "str1=This is Test string"Set "sstr=Test"call :strlen str1 len1call :strlen sstr len2set /a stop=len1-len2if %stop% gtr 0 for /l %%i in (0,1,%stop%) do if "!str1:~%%i,%len2%!"=="%sstr%" set /a position=%%iif defined position (echo.Position of %sstr% is %position%) else echo."%sstr%" not found in "%str1%"goto :eof:strlen:: list string length up to 8189 (and reports 8189 for any string longer than 8189:: function from http://ss64.org/viewtopic.php?pid=6478#p6478(   setlocal enabledelayedexpansion & set /a "}=0"    if "%~1" neq "" if defined %~1 (        for %%# in (4096 2048 1024 512 256 128 64 32 16) do (            if "!%~1:~%%#,1!" neq "" set "%~1=!%~1:~%%#!" & set /a "}+=%%#"        )        set "%~1=!%~1!0FEDCBA9876543211" & set /a "}+=0x!%~1:~32,1!!%~1:~16,1!"    ))endlocal & set /a "%~2=%}%" & exit /bendlocal

If %str1% contains more than one %sstr%, the code will find the last position.