"FOR" help

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Odder93
Posts: 11
Joined: 15 Jul 2008 12:43
Contact:

"FOR" help

#1 Post by Odder93 » 20 Jul 2008 03:17

Hello, I'm pretty new at this coding language, but I think I've got a bit experience :-)

My problem is: I do not understand ANYTHING of the "FOR" command, is it possible for you to explain me how that "function" works? I see it's very usefull xD

greenfinch
Posts: 36
Joined: 17 Jul 2008 07:37

#2 Post by greenfinch » 21 Jul 2008 06:40

I found this very useful:
http://www.robvanderwoude.com/for.html

It helps to think:
FOR every TOKEN in (list, file, whatever) DO (something involving the token)

That's the basic format. The delims=, tokens= and so on basically let you get the right token to do things to - worry about that later.

Tigers!
Posts: 6
Joined: 01 Jul 2008 21:57
Location: Australia

#3 Post by Tigers! » 21 Jul 2008 17:25

Good post Greenfinch. I am glad that you are onboard.

Odder93
Posts: 11
Joined: 15 Jul 2008 12:43
Contact:

#4 Post by Odder93 » 23 Jul 2008 10:49

Thanks for your reply :D

So, if I want to make a command to:

... make the same file twice, at two different locations:
FOR %a IN (%USERPROFILE%\desktop %USERPROFILE%\documents) DO echo start %CD% >> %a

... count to 20
FOR %a IN (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20) DO echo %a
hmm.. I would normally do something like:
:loop
IF /I %a% GEQ 20 (goto end)
echo %a%
set /a a=%a%+1
goto loop

... to make 2 word "listings" (This is a wild guess
:wink: )
FOR %a IN (greetings, %yourname%, ., Please type your something) DO echo %a


okay... can you guys please correct me if I'm wrong? :P

EDIT: forgot to bold half of one of the command lines xD

greenfinch
Posts: 36
Joined: 17 Jul 2008 07:37

#5 Post by greenfinch » 23 Jul 2008 11:12

Just about right, yes!

In the first example, you need to specify a filename to output to within %a, e.g.

Code: Select all

FOR %a IN (%USERPROFILE%\desktop %USERPROFILE%\documents) DO echo start %CD% >> %a\filename.txt


Your final example is more fiddly:

Code: Select all

FOR /f "delims=, tokens=1-3" %a IN ("greetings %yourname%,., Please type your something") DO echo %a&&echo%b&&echo%c


Here the /f switch enables use of the delims and tokens, you state that the delimiter is , and there are 3 tokens

Quotes are added to ("set") because (set) refers to a file, rather than a string

&& means "if the last command went OK, do this"

There might be a simpler way of doing this - still learning myself!

Odder93
Posts: 11
Joined: 15 Jul 2008 12:43
Contact:

#6 Post by Odder93 » 23 Jul 2008 11:21

Ok thanks again :D

The last was just to test your knownledge :wink:

and I see the problem in line 1, it might be one of the "random-error" I do :p

Post Reply