Use 1 variable for all tokens in for-loop

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Reino
Posts: 23
Joined: 14 May 2015 06:13
Contact:

Use 1 variable for all tokens in for-loop

#1 Post by Reino » 01 Jun 2020 09:01

My apologies if this has been asked before.

'input.txt':

Code: Select all

test1
test2
test3
When you open 'input.txt' (with every string on a new line) in a for-loop (directly, or through a command), it will use the same %A for each line, as expected:

Code: Select all

FOR /F %A IN (input.txt) DO @ECHO -%A
-test1
-test2
-test3

FOR /F %A IN ('TYPE input.txt') DO @ECHO -%A
-test1
-test2
-test3
When using a variable on the other hand, and despite <space> being a default delimiter, you'd have to use tokens and another variable for every token, which I find very strange:

Code: Select all

SET str=test1 test2 test3

FOR /F "tokens=1-3" %A IN ("%str%") DO @(
More?   ECHO -%A
More?   ECHO -%B
More?   ECHO -%C
More? )
-test1
-test2
-test3
In Bash a <space> is also a delimiter by default, but the same variable is used for each token, as expected:

Code: Select all

str="test1 test2 test3"

for a in $str; do echo -$a; done
-test1
-test2
-test3
Is this "trick"...

Code: Select all

SET str=test1 test2 test3

FOR /F %A IN ('ECHO.%str: =^&ECHO.%') DO @ECHO -%A
-test1
-test2
-test3
...the only way to do that in CMD/Batch?

Squashman
Expert
Posts: 4465
Joined: 23 Dec 2011 13:59

Re: Use 1 variable for all tokens in for-loop

#2 Post by Squashman » 01 Jun 2020 10:31

Take out the /F option.

Code: Select all

SET str=test1 test2 test3
FOR %%A IN (%str%) DO @ECHO -%%A

Reino
Posts: 23
Joined: 14 May 2015 06:13
Contact:

Re: Use 1 variable for all tokens in for-loop

#3 Post by Reino » 01 Jun 2020 15:29

I thought /F was always needed to process strings.
I didn't know this. Thanks.

Post Reply