Save textlines to respective variables

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
(_osd_)
Posts: 25
Joined: 01 Mar 2015 07:41

Save textlines to respective variables

#1 Post by (_osd_) » 18 Sep 2016 04:58

Hello!
I have a textfile called "abc.tmp" and it has 500 lines, in every line is one number.
I want every number to be saved in a variable that is respective to the line it got from, so:

These are the first 5 lines of "abc.tmp":
3
4
0
2
1

And I want the first line (3) to be saved to mvm1,
the second line (4) to be saved to mvm2,
the third line (0) to be saved to mvm3,
the fourth line (2) to be saved to mvm4,
the fifth line (1) to be saved to mvm5,
...

So that all 500 lines of the file are in mvm1 to mvm500. How can you do that?

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Save textlines to respective variables

#2 Post by aGerman » 18 Sep 2016 05:07

Yes you can do that. FINDSTR /N prepends a line number to each line, separated with a colon. You can process this output using FOR /F.
untested:

Code: Select all

for /f "tokens=1* delims=:" %%i in ('findstr /n . "abc.tmp"') do set /a "mvm%%i=%%j"


Note: You should avoid that! Better process the lines directly in the loop.

Steffen

(_osd_)
Posts: 25
Joined: 01 Mar 2015 07:41

Re: Save textlines to respective variables

#3 Post by (_osd_) » 18 Sep 2016 05:15

@AGerman Thanks, it works! Why is that better though?

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Save textlines to respective variables

#4 Post by aGerman » 18 Sep 2016 06:12

- Loading variables into the process environment takes time.
- The bigger the environment the worse the performance of you script.

Although I don't know your final goal. Thus, I don't know if it would be even possible to work with the FOR variables directly in the body of a loop.

Steffen

(_osd_)
Posts: 25
Joined: 01 Mar 2015 07:41

Re: Save textlines to respective variables

#5 Post by (_osd_) » 18 Sep 2016 07:03

@aGerman Ok... So how can I do that?

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Save textlines to respective variables

#6 Post by aGerman » 18 Sep 2016 08:11

As I said - I don't know your final goal. Without having a crystal ball ...

Code: Select all

for /f "tokens=1* delims=:" %%i in ('findstr /n . "abc.tmp"') do (
  echo do something with %%j in line %%i
)

or simply

Code: Select all

for /f "usebackq delims=" %%i in ("abc.tmp") do (
  echo do something with %%i
)

Steffen

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Save textlines to respective variables

#7 Post by foxidrive » 20 Sep 2016 05:17

(_osd_) wrote:@aGerman Ok... So how can I do that?


Here are some tips for you.

See here: viewtopic.php?f=3&t=6108

Post Reply