SHARE
TWEET

Get random line from textfile in batch (BATCH)

Imthedude025 Sep 21st, 2018 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. @ECHO OFF
  2. SETLOCAL
  3. SETLOCAL EnableDelayedExpansion EnableExtensions
  4.  
  5. REM Source file.
  6. REM The first line on this file should be blank as it will never be selected.
  7. REM Additionally, this file should have no empty lines on the end.
  8. SET "TextFile=q27829742.txt"
  9.  
  10. REM Determine the number of lines.
  11. FOR /f %%a IN ('type "%textfile%"^|find /c /v ""') DO SET /a numlines=%%a
  12.  
  13. REM Pick a random line.
  14. SET /A RandomLine=(%RANDOM% %% %NumLines%)
  15.  
  16. REM Prevent skipping all the lines.
  17. IF "%RandomLine%"=="0" (SET "RandomLine=") ELSE (SET "RandomLine=skip=%randomline%")
  18.  
  19. REM Print the random line.
  20. FOR /F "usebackq tokens=* %RandomLine% delims=" %%A IN (`TYPE %TextFile%`) DO (
  21.     ECHO %%A
  22.     REM We are done. Stop the script.
  23.     GOTO Finish
  24. )
  25.  
  26. :Finish
  27. ENDLOCAL
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top