|
Answer» i am creating a batch file that requires me to read a random line in a .txt file. for example it WOULD find the random line in file.txt and display it onscreen. i need to search through a 200-line .txt file and pull a random line. then it would be echoed onscreen. i figured someone would have a fancy FOR script for this.@echo off REM test.txt is a file of 200 lines REM this script will select a line at random REM and echo it on screen
set linecount=200 set /a number=(%random% %% %linecount%)+1 For /f "skip=%number% delims=" %%L in ('type test.txt') do set line=%%L & goto next :next echo %line%
YES, it can be done in a Batch file. Do you intend to invoke it from another program or batch file? Here is a very simple program to do only ten lines of text. Code: [Select]echo please wait.. echo off :loop set num=%randOM% if %num% GTR 5 goto loop if %num% LSS 1 goto loop echo number %num% if %num%==1 goto goblin if %num%==2 goto wolf if %num%==3 goto cat if %num%==4 goto girl if %num%==5 goto dragon :goblin echo Goblin creature is attacking you! goto EXIT :wolf echo Wolf creature is attacking you! goto exit cat: echo Cat creature is attacking you! goto exit girl: echo Girl creature is attacking you! goto exit :dragon echo Dragon creature is attacking you!
:exit OK, that is not what you asked for, but it is a start. edit: My code does not use a FOR loop. The Salmon Trout code is MUCH better.Quote from: Geek-9pm on July 30, 2013, 10:59:47 AM Girl creature is attacking you!
This is the one I prefer. @echo off setlocal enabledelayedexpansion set linecount=200 set /a randnum=%random% %% %linecount%+1 set tempnum=1 For /f "delims=" %%L in ('type test.txt') do ( if !tempnum! equ %randnum% ( set line=%%L goto next ) set /a tempnum+=1 ) :next echo %line%
This is better than my previous effort, which would never show the first line of the input text file.
|