# Batch File -- Read Random Line from External File into an Environment Variable



## encryptedbytes (Sep 27, 2007)

I've been searching the web on how to accomplish this but am coming up empty handed so I am hoping someone here can help...

I want my batch file to read a random line from a text file into an environment variable - can this be done?

I am using Windows 2000.


----------



## JohnWill (Oct 19, 2002)

How does it find this "random" line in the file?


----------



## encryptedbytes (Sep 27, 2007)

I guess I am not sure...

The file I want to read from will have a list of "agents" like so:

Agent #1
Agent #2
Agent #3
Agent #4
Agent #5 (and so on...)

I want to select one of them randomly and shove that line into an environment variable. I am thinking maybe there's a way to read the number of lines in the file into a variable (X), then generate a random integer between 1 and X (Y), and then read line Y into another variable %AGENT% that I can use as a paramenter in a program the batch file is running.

I wish I knew more about this stuff


----------



## JohnWill (Oct 19, 2002)

I don't know how to do this with a plain batch file, I'd probably write a 20 line C++ program to do it.


----------



## ghostdog74 (Dec 7, 2005)

encryptedbytes said:


> I've been searching the web on how to accomplish this but am coming up empty handed so I am hoping someone here can help...
> 
> I want my batch file to read a random line from a text file into an environment variable - can this be done?
> 
> I am using Windows 2000.


i won't do the batch for you, but some suggestions
1) use %random% variable to generate the random number
2) use a for loop to iterate the file, then count the number of lines in the file. store in variable
3) find a way to "normalize" the random number to fit inside the range from 1 to the number of lines found in 2)
eg set /a getline=%random%%10 . (for 10 lines). You can derive your own way to come up with a number in the range
4) then iterate the file again, but this time when the counter hits getline, print the line out and exit. remember to store this to whatever environment variable you are using...


----------

