For isacmahad

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

For isacmahad

#1 Post by avery_larry » 05 Nov 2009 17:20

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

isacmahad
Posts: 44
Joined: 29 Oct 2009 23:08

#2 Post by isacmahad » 05 Nov 2009 18:33

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.

isacmahad
Posts: 44
Joined: 29 Oct 2009 23:08

#3 Post by isacmahad » 05 Nov 2009 18:41

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.

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

#4 Post by avery_larry » 06 Nov 2009 10:49

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.

Post Reply