Page 1 of 1

Save textlines to respective variables

Posted: 18 Sep 2016 04:58
by (_osd_)
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?

Re: Save textlines to respective variables

Posted: 18 Sep 2016 05:07
by aGerman
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

Re: Save textlines to respective variables

Posted: 18 Sep 2016 05:15
by (_osd_)
@AGerman Thanks, it works! Why is that better though?

Re: Save textlines to respective variables

Posted: 18 Sep 2016 06:12
by aGerman
- 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

Re: Save textlines to respective variables

Posted: 18 Sep 2016 07:03
by (_osd_)
@aGerman Ok... So how can I do that?

Re: Save textlines to respective variables

Posted: 18 Sep 2016 08:11
by aGerman
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

Re: Save textlines to respective variables

Posted: 20 Sep 2016 05:17
by foxidrive
(_osd_) wrote:@aGerman Ok... So how can I do that?


Here are some tips for you.

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