Page 1 of 1
For isacmahad
Posted: 05 Nov 2009 17:20
by avery_larry
Code: Select all
@echo off
set "string=hel $howe owe $sodfi asf$wer23 wer"
for /f "tokens=1* delims=$" %%a in ("%string%") do if not "%%~b"=="" call :recurse "%%~b"
goto :eof
:recurse
for /f "tokens=1*" %%a in ("%~1") do (
echo %%a
for /f "tokens=1* delims=$" %%a in ("%~1") do if not "%%~b"=="" call :recurse "%%~b"
)
goto :eof
Posted: 05 Nov 2009 18:33
by isacmahad
Thank you very very much. This is a much better solution, no hang ups straight and to the point. Of course leave it me me to code more than I have to. I'm still learning this is why I reach out to the community. Avery your solution is superb for what I am trying to accomplish. Now the blocks of if statements can be nicely implemented where need be. Again thank you for this clean clear example. Works beautifully.
Posted: 05 Nov 2009 18:41
by isacmahad
If it is not to much trouble, explain to me how the "if not" statements in the for loops work it would be greatly appreciated. The script works and I understand the for commands but do not understand the do commands.
Again thank you.
Posted: 06 Nov 2009 10:49
by avery_larry
for /f "tokens=1* delims=$" %%a in ("%string%") do if not "%%~b"=="" call :recurse "%%~b"
This for statement will have 2 tokens defined, using $ as the delimiter. %%a will be defined as everything up to the first $ (token #1), and %%b will be defined as everything after the first delimiter (or technically, the first set of delmiters, since a for statement treats a group of delimiters as a single delimiter). Since we only care about whatever comes after a $, we just ignore the first token -- %%a. The if statement is basically saying -- if %%b is nul -- then we don't want to do anything. Of course, if %%b is nul, then there either wasn't a $ in the line, OR there was nothing after the $ in the line.
Inside the :recurse subroutine, we know that we will only call the subroutine with a string that begins immediately after a $. Thus we use a typical for loop (using whitespace as the delimiter) to simply echo the first token. Then we essentially start over. The nested for loop will take a look at the string and see if there are any more $'s and recursively call itself with the rest of the string after the next $. Again, if %%b is nul, then we've reached the end of the $'s in the string and we can just be done.