Reputation: 501
I have a text file (text.txt) that lists a person's name followed by their favorite color (see below). I want to assign the variable "name" to the person's name and the the variable "color" to the person's favorite color.
Right now, my code correctly pulls the name by skipping every other line, but it is not assigning the person's favorite color. Any assistance is much appreciated.
text.txt
john
blue
matt
red
susan
yellow
My script:
@echo off
setlocal enabledelayedexpansion
set x=0
for /f "delims=" %%a in (C:\text.txt) do (
set /a "x=(x+1) %% 2"
if !x! == 1 set color=%%a
if !x! == 0 call echo !color!
)
Current output:
john
matt
susan
Upvotes: 1
Views: 118
Reputation: 67216
Perhaps this method is simpler/clearer:
@echo off
setlocal enabledelayedexpansion
set "name="
for /f "delims=" %%a in (C:\text.txt) do (
if not defined name (
set "name=%%a"
) else (
echo !name!,%%a
set "name="
)
)
Upvotes: 2
Reputation: 140178
There's a logic problem in your loop. You have to read the name first, then the color and only print when you have both information.
@echo off
setlocal enabledelayedexpansion
set x=0
for /f "delims=" %%a in (text.txt) do (
if !x! == 0 set name=%%a
if !x! == 1 (
set color=%%a
echo !name!,!color!
)
set /a "x=(x+1) %% 2"
)
result:
john,blue
matt,red
susan,yellow
Upvotes: 2