1

I have a text file with the following format:

name1:surname1
name2:surname2
name3:surname3

and so on.

I need to write a for loop in window batch script and assign to 2 variables

name=name1
surname=surname1

and so on. Something like (this is wrong)

for /F "tokens=*" %%row in (myfile.txt) do (
for /F "tokens=1* delims=:" %%u in ("%row%") do (
 .... 
 )
)

Any suggest?

3 Answers 3

2

You don't really need two nested loops for that.

What you probably will need, however, is delayed variable expansion.

@echo off
setlocal enabledelayedexpansion

for /f "tokens=1,2 delims=:" %%u in (myfile.txt) do (
    set "name=%%u"
    set "surname=%%v"

    echo !surname!, !name!
)

outputs this for me:

surname1, name1
surname2, name2
surname3, name3

Delayed variable expansion is what allows you to assign the single-letter loop variables (u and v in this case) to real variables and use them in the rest of the loop, by accessing them with ! instead of %.

Sign up to request clarification or add additional context in comments.

Comments

2
for /F "tokens=*" %%r in (myfile.txt) do (
for /F "tokens=1* delims=:" %%u in ("%%r") do (
 .... 
 )
)

or

for /F "tokens=1* delims=:" %%u in (myfile.txt) do (
.... 
)

Metavariables live r and u are limited to a single (case-sensitive) alphabetical character.

Comments

0
@echo off
setlocal EnableDelayedExpansion

for /F "tokens=1,2 delims=:" %%u in (myfile.txt) do (
    set name=%%u
    set surname=%%v

    echo name=!name!
    echo surname=!surname!
)

output:

name=name1
surname=surname1
name=name2
surname=surname2
name=name3
surname=surname3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.