dimanche 12 juin 2016

Batch File: Assign random line of text file as variable for later use

I'm trying to write a very simple batch file for personal use...It's complete except for one thing I'm stumped on. Hopefully this is an easy fix (I'm effectively illiterate when it comes to code).

Basically what I'm trying to do is have the script choose a random line from a text file, do this a couple times with a couple different text files, then I wish to assign the output from each text file to a variable so that I can easily use them in various combinations...then repeat the process. Here is what I have right now...

@ECHO OFF
:START
SETLOCAL
SETLOCAL EnableDelayedExpansion EnableExtensions

SET "list1=list1.txt"
FOR /f %%a IN ('type "%list1%"^|find /c /v ""') DO SET /a numlines=%%a
SET /A list1random=(%RANDOM% %% %NumLines%)
IF "%list1random%"=="0" (SET "list1random=") ELSE (SET "list1random=skip=%list1random%")
FOR /F "usebackq tokens=* %list1random% delims=" %%A IN (`TYPE %list1%`) DO (
    >> output.txt ECHO %%A
)
:Finish
ENDLOCAL
GOTO START`

This procures the random line, and spits it to a text file. All is well, next step, take that random result and assign it to a variable...

@ECHO OFF
:START
SETLOCAL
SETLOCAL EnableDelayedExpansion EnableExtensions

SET "list1=list1.txt"
FOR /f %%a IN ('type "%list1%"^|find /c /v ""') DO SET /a numlines=%%a
SET /A list1random=(%RANDOM% %% %NumLines%)
IF "%list1random%"=="0" (SET "list1random=") ELSE (SET "list1random=skip=%list1random%")
FOR /F "usebackq tokens=* %list1random% delims=" %%A IN (`TYPE %list1%`) DO (
    SET output1=%%A
)
>> output.txt ECHO %output1%
:Finish
ENDLOCAL
GOTO START

Now the output ceases to be random...instead it is always the last line of the referenced text file.

I appreciate any help in advance, this is the last step before I know everything I need to finish this, I'm excited!




Aucun commentaire:

Enregistrer un commentaire