开发者

Batch script to extract a string from a file

I've looked around for some string manipulation routines, and am aware that I could do this in several other languages, but I'd like it in a batch file for simplicity.

I wish it to search an XML file for a tag and extract everything from there to the end of the file.

So I guess, for example in pseudo-javascript:

marketIndex = str.indexOf("<Markets>");
length = str.length;
marketString = str.substring(markeIndex, length-1);
return str;

I have a substring function in bat:

:Substring
::Substring(retVal,string,startIndex,length)
:: extracts the substring from string starting at startIndex for the specified length 
 SET string=%2%
 SET startIndex=%3%
 SET length=%4%

 if "%4" == "0" goto :noLength
 CALL SET _substring=%%string:~%startIndex%,%length%%%
 goto :substringResult
 :noLength
 CALL SET _substring=%%string:~%startIndex%%%
 :substringResult
 set "%~1=%_substring%"
GOTO :EOF

and a length of a string function:

:StrLength
::StrLength(retVal,string)
::returns the length of the string specified in %2 and stores it in %1
set #=%2%
set length=0
:stringLengthLoop
i开发者_JAVA技巧f defined # (set #=%#:~1%&set /A length += 1&goto stringLengthLoop)
::echo the string is %length% characters long!
set "%~1=%length%"
GOTO :EOF

so I guess I'm missing an indexOf() function in bat...


rem indexof result haystack needle
:indexof
setlocal enabledelayedexpansion enableextensions
set result=
set "haystack=%~2"
call :strlength length %3
call :strlength haylength %2
set /a max=haylength-length
for /l %%i in (0,1,%max%) do (
    if "!haystack:~%%i,%length%!"=="%~3" (set result=%%i&goto indexofDone)
)
set result=-1
:indexofDone
endlocal && set %~1=%result%
goto :eof

Also available in my SVN. Note that I altered the definition of strLength to fix some bugs:

:strlength
setlocal enableextensions
set "#=%~2"
set length=0
:stringLengthLoop
if defined # (set "#=%#:~1%"&set /A length+=1&goto stringLengthLoop)
endlocal && set "%~1=%length%"
GOTO :EOF

Note further, that all this will not help you at all as parsing XML with batch files is not something you should do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜