JSI Tip 4194. How do I determine the position of a sub-string in a string?


NOTE: See tip 9485 » A better way to determine the position and length of a sub-string in a string.

NOTE: See tip 9470 » A better way to determine the length of a string.

Using $PosLen and $Length, I have scripted $Position.bat.

The usage syntax is:

$position string sub-string.

$Position.bat returns a $Pos numeric environment variable with the position, from 0, of the sub-string, and a $len numeric environment variable with the length of the sub-string. If the sub-string is not found, the $len environment variable is set to 0.

$Position.bat contains:

@echo off
setlocal
set /a $pos=0
set /a $len=0
set string=####%1####
set string=%string:####"=%
set string=%string:"####=%
if "%string%" EQU "" goto end
set string=%string:####=%
set substring=####%2####
set substring=%substring:####"=%
set substring=%substring:"####=%
if "%substring%" EQU "" goto end
set substring=%substring:####=%
for /f "Tokens=*" %%k in ('@echo %%string:%substring%^=%%') do @set $work$=%%k
if "%look%" EQU "%$work$%" goto end
call $length "%string%"
if %$len% EQU 0 goto end
set /a len=%$len%
call $length "%substring%"
if %$len% EQU 0 goto end
set /a pos=0
:loop
if %pos% GTR %len% set /a $len=0&goto end
call $poslen "%string%" %pos% %$len%
if "%$substring%" EQU "%substring%" set /a $pos=%pos%&goto end
set /a pos=%pos% + 1
goto loop
:end
endlocal&set /a $pos=%$pos%&set /a $len=%$len%
REM end $Position

Demonstration of usage:

To locate every entry in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers that contains the %LogonServer% computer name, run:
@echo off
regedit /a %TEMP%\temp.reg "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers"
set ls=%logonServer:\=%
set /a seq=0
for /f "Tokens=*" %%i in (%TEMP%\temp.reg) do set line=%%i&call :parse
del /f /q %TEMP%\temp.reg
goto :EOF
:parse
set look=%line:"=*%
call $poslen "%look%" 0 1
if "%$substring%" EQU "\[" set key=%line%
set /a seq=%seq% + 1
call $position "%look%" %ls%
if %$len% EQU 0 goto :EOF
@echo line:%seq% 
@echo key:%key% 
@echo Position:%$pos%
@echo Length:%$Len% 
@echo Data:%line%
@echo.
The output would look similar to:
line:435
key:\[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers\HP Business Inkjet 2250 PCL 5C\]
Position:12
Length:6
Data:"Port"="\\\\JSI001\\HP2250"

line:706
key:\[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers\HP Business Inkjet 2250 PS\]
Position:12
Length:6
Data:"Port"="\\\\JSI001\\HP2250"
NOTE: See tip 4192 » How can I determine if a string contains a specific sub-set of characters?



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish