Reputation: 37
I'm trying to make a Character_Picker.bat
that echo a randomly picked string from a characters.txt
a long text file. I have no idea how to do a random pick.
Characters.txt:
Disco Jockey Acid Pol
Double Agent Acid Pol
Muaythai Acid Pol
Paramedic Acid Pol
WWII Acid Pol
WWII Acid Pol
PB Quinn Chou
Secret Agent Chou
Rider Chou
General Chou
Grim Reaper Chou
Psycho Nurse Chou
Highschool Chou
Invasion Chou
Army Agent Chou
Kung Fu Chou
Rogue Agent Chou
Sweet Heart Chou
.
.
.
.333 strings more
My Batch Code:
@echo off
color a
cd Desktop
start "characters.txt" ==> this is the thing where I stuck
set /a string=%random% %% 334
echo %string%
Upvotes: 1
Views: 2227
Reputation:
I think this is what you want.
@echo off
set /a rand=%random% %% 334
for /f "tokens=1* delims=:" %%i in ('findstr /n .* "d:\characters.txt"') do (
if "%%i"=="%rand%" echo %%j
)
We set rand
and limit the random numbers to 334.
We then read the file and findstr the line number, if that number matches the random string, print the string.
just so you understand the delims=:
portion. findstr /n .* "d:\characters.txt"
will print the line number, then a colon and the actual line. Something like:
1:Disco Jockey Acid Pol
2:Double Agent Acid Pol
3:Muaythai Acid Pol
4:Paramedic Acid Pol
5:WWII Acid Pol
....
delims=:
uses the :
as delimiter and we assign line number to %%i
and the actual line text to %%j
Hence matching %%i
with %rand%
and then printing %%j
for doing multiple random runs, add a for /l
loop, this example will do 4 random lines:
@echo off
for /l %%a in (1,1,4) do call :run
goto :EOF
:run
set /a rand=%random% %%334
for /f "tokens=1* delims=:" %%i in ('findstr /n .* "d:\characters.txt"') do (
if "%%i"=="%rand%" echo %%j
)
or to prompt you each time how many randoms you'd like:
@echo off
set /p num=How many?
for /l %%a in (1,1,%num%) do call :run
goto :EOF
:run
set /a rand=%random% %%334
for /f "tokens=1* delims=:" %%i in ('findstr /n .* "d:\characters.txt"') do (
if "%%i"=="%rand%" echo %%j
)
Upvotes: 2
Reputation: 34949
I would at first determine the number of lines in the text file, then determine a random number in that range, and then extract exactly this line, like this:
@echo off
for /F %%C in ('^< "characters.txt" find /C /V ""') do set "COUNT=%%C"
set /A "NUMBER=%RANDOM%%%%COUNT%"
if %NUMBER% gtr 0 (set "SKIP=skip=%NUMBER%") else (set "SKIP=")
for /F usebackq^ %SKIP:skip=skip^%^ delims^=^ eol^= %%L in ("characters.txt") do (
echo(%%L
goto :NEXT
)
:NEXT
If the target line is empty, then the next non-empty one would be returned by this code.
This approach supports text files with not more than 32768 lines.
Upvotes: 1