Dan
Dan

Reputation: 842

Batch file: set variables using a dynamic number of tokens

I am reading through a file using a batch script. Basically I want to read a specific line and set its tokens to different variables. The problem is, the line does not have a fixed number of tokens. Consider the following file format:

Line 1 Domains www.google.com www.yahoo.com www.reddit.com ...
Line 2 541 5435 322 123
Line 3 273 123 432 123

My script will be reading the line whose third token equals "Domains" and store the tokens that follow into different variables. In this case, I would set Domain1=www.google.com, Domain2=www.yahoo.com, Domain3=www.reddit.com, and so on. My code will look something like this:

for /f "tokens=3*" %%A in (%file%) do (
    if ("%%A"=="Domains") (
        REM Delimit %%B with a space and store each token into different variables
    )
)

EDIT: Problem solved. It is too soon for me to answer my own question due to insufficient rep, but here is my solution starting from Jeremy's post:

set index=1
for /f "tokens=3*" %%A in (%file%) do (
    if ("%%A"=="Domains") (
        for %%C in (%%B) do (
            set Domain!index!=%%C
            set /A index+=1
        )
    )
)

Upvotes: 2

Views: 3383

Answers (1)

Jeremy E
Jeremy E

Reputation: 3704

This doesn't solve your problem exactly the way you wanted it solved but I think this is a workable solution:

@echo off

for /f "tokens=3*" %%A in (%file%) do (
  if "%%A"=="Domains" (
    set domains=%%B
  )
)

for %%A in (%domains%) do (
  echo %%A
)

Upvotes: 2

Related Questions