-1

Sorry if this has been asked before, I couldn't find anything though specifically for this.

I have a list.txt with a new word on each line, like

do
re
me
fa
something
somethingelse

How can I grab a random word (assuming the list has a random amount of lines)and set it as a %variable%?

I'm pretty sure I would need the "for" command but I've got no idea how to use it lol

Thanks

Edit: my bad I should've specified this is in Windows Batch

TTT
  • 97
  • 2
  • 5
  • 1
    https://stackoverflow.com/help/how-to-ask – ecg8 Dec 14 '18 at 02:07
  • With PowerShell this is trivial `powershell -NoP -C "Get-Content .\file.txt|Get-Random"` could easily be wrapped in a batch. The title should ask for a random line not word. –  Dec 14 '18 at 10:01

1 Answers1

1

try this (you'll have to change the path to the file on the third line):

@echo off
setlocal
set "file=words.txt"

for /f %%# in (
    'findstr  /r /n "^" "%file%" ^|find /c ":"'
) do (
    set lines=%%#
)

set /a random_line=(%RANDOM%*%lines%/32768)

for /f "usebackq skip=%random_line%" %%# in ("%file%") do (
    set "random_word=%%#"
    goto :break
)   
:break

echo %random_word%
endlocal

UPDATE:

@echo off
setlocal
set "file=words.txt"

for /f %%# in (
    'findstr  /r /n "^" "%file%" ^|find /c ":"'
) do (
    set lines=%%#
)

set /a random_line=random_line=%random% %% %lines%

if random_line==0 (
    set "skip="
) else (
    set "skip=skip=%random_line%"
)

for /f "usebackq %skip%" %%# in ("%file%") do (
    set "random_word=%%#"
    goto :break
)   
:break

echo %random_word%
endlocal
npocmaka
  • 55,367
  • 18
  • 148
  • 187