Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 400 Vote(s) - 3.47 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to iterate string in cmd for loop?

#1
I am trying to iterate a string in batch script:

set var="1 2 3"

for /F %%i in (%var%) do (
echo %%i
)

and getting this output:

C:\>batch.bat


C:\>set var="1 2 3"

C:\>for /F %i in ("1 2 3") do (echo %i )

C:\>(echo 1 )
1

I expect that all 3 numbers will be printed:

1
2
3

What am I doing wrong?
Reply

#2
Try `FOR` in place of `FOR /F`. Also, quoting the value when setting `var` is unnecessary:

set var=1 2 3

for %%i in (%var%) do (
echo %%i
)
Reply

#3
Because `FOR /F` loops every line of a text file, and when used with a string (`""` quoted) it only do things on that line. It *does* delimit by whitespace, but that is to be used with the option `tokens`.

You should use `FOR`

set var=1 2 3

for %%i in (%var) do (
echo %%i
)

If you want to loop numbers, use the following:

for /L %%i in (1,1,3) do (
echo %%i
)
Reply

#4
That's because FOR/F splits a each line into multiple tokens, but you need to define how many tokens you want to process.

set var="1 2 3"

for /F "tokens=1-3" %%i in (%var%) do (
echo %%i
echo %%j
echo %%k
)

**EDIT:** Other solutions

Like the answer of Ed harper:
You could also use a normal FOR-loop, with the limitation that it will also try to serach for files on the disk, and it have problems with `*` and `?`.

set var=1 2 3

for %%i in (%var%) do (
echo %%i
)

Or you use **linefeed technic** with the FOR/F loop, replacing your delim-character with a linefeed.

setlocal EnableDelayedExpansion
set LF=^


set "var=1 2 3 4 5"
set "var=%var: =!LF!%"
for /F %%i in ("!var!") do (
echo %%i
)

This works as the FOR/F sees five lines splitted by a linefeed instead of only one line.
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through