How could one select a random line of text from a text file and set it in a variable to use?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s yet another approach. It reads the file name from the command line and uses a
FOR /Lloop to get to the calculated line number:The
FOR /Floop simply gets the number of lines in the file (the method is borrowed from @Aacini’s answer).A rather simplistic formula then calculates the number of lines to skip in the file.
Next, the file is read. The
FOR /Lloop merely consumes the specified number of lines using aSET /Pinstruction. Following the loop, one moreSET /Pcommand reads the line that is eventually ECHOed.The above implementation is just to show the basic idea. It is not without issues, but some of them could easily be resolved:
There’s no testing whether the parameter is indeed supplied. If it is absent, the script will break. You could add the necessary check at the beginning of the script like this:
If there’s no parameter, this command terminates the script by sending the control to the end of the script (
GOTO :EOF).The file specified might not exist. Again, you could test that at the beginning, just after verifying that the parameter is supplied, to terminate the script if necessary:
If the file is empty, the
lineswill be0and the subsequent expression using it will run into a division by zero error. Therefore, you’ll also need to test the resulting line count (and prevent the script from running further if the count is indeed 0). You can do that by adding the following line just after theFOR /Floop:Like I said, the formula is somewhat simplistic. It doesn’t produce a number greater than 32767, which is the limitation of
%RANDOM%. That might well be enough for you, but in case it is not, you could extend the range to 230-1 using two%RANDOM%calls like this:So, here’s the same script again, amended to address the above mentioned issues:
One other note is that, if you like, you can add messages explaining the reason for the premature termination of the script. Basically, wherever you want to add the message, you’ll just need to replace the single
with
For instance: