Page 1 of 1

Use 1 variable for all tokens in for-loop

Posted: 01 Jun 2020 09:01
by Reino
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?

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

Posted: 01 Jun 2020 10:31
by Squashman
Take out the /F option.

Code: Select all

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

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

Posted: 01 Jun 2020 15:29
by Reino
I thought /F was always needed to process strings.
I didn't know this. Thanks.