sunny24365
sunny24365

Reputation: 563

Getting token values from for loop in Windows Batch

I'm new to Windows batch scripting. Trying to get values out of text file, Ignore.txt file and store them as local variables.

Command File:

@Echo off
setlocal enabledelayedexpansion

for /F "tokens=1,2,3" %%i in (Ignore.txt) do (
    echo. %%i
    echo. %%j
    echo. %%k

  set value1=%%i
  set value2=%%j
  set value3=%%k
)

Echo. Value1: !value1!
Echo. Value2: !value2!
Echo. Value3: !value3!

Endlocal

Ignore.txt:

*.svc
*.jpg
*.png

But the result is only printing one variable that too wrong:

Output:

 *.svc
 *.jpg
 *.png

 Value1: *.png
 Value2:
 Value3:

Please help me if I'm doing anything wrong here. Also any suggestions on other better ways of retrieving this information.

Upvotes: 1

Views: 2986

Answers (2)

tecdoc ukr net
tecdoc ukr net

Reputation: 134

The main difficulty in your case is that the FOR loop does not know how to set newline characters as a delimiter. So first you need to discard the newline character, such as collecting all the lines of a file into a text variable with a specific delimiter. After which it becomes possible to obtain the values of several variables.

SETLOCAL EnableDelayedExpansion

:: Catenate all file lines in the same variable separated by %del%
SET "text="
SET "del=~"
FOR /F %%a IN (Ignore.txt) DO (SET "text=!text!%del%%%a")
ECHO %text%

:: obtain the values of several variables.
FOR /F "delims=%del% tokens=1-6" %%i IN ("%text%") DO (
  echo. %%i
  echo. %%j
  echo. %%k

  set value1=%%i
  set value2=%%j
  set value3=%%k
)
Echo. Value1: !value1!
Echo. Value2: !value2!
Echo. Value3: !value3!

Output

 *.svc
 *.jpg
 *.png
 Value1: *.svc
 Value2: *.jpg
 Value3: *.png

Upvotes: 0

Anon Coward
Anon Coward

Reputation: 10827

The help for for's token option contains this bit:

tokens=x,y,m-n  - specifies which tokens from each line are to
                 be passed to the for body for each iteration.

In other words, it will only split a single line into multiple variables. This is evidenced by the run of your script: It outputs each line, but it's outputting empty lines between each one where the empty %%j and %%k are.

If you want to parse this file into separate variables, you'll need to track which line you're on manually, with something like this:

@Echo off
setlocal enabledelayedexpansion

set _digit=1
for /F %%i in (Ignore.txt) do (
    echo. %%i

    set value!_digit!=%%i
    set /a _digit=!_digit!+1
)

Echo. Value1: !value1!
Echo. Value2: !value2!
Echo. Value3: !value3!

Endlocal

Upvotes: 1

Related Questions