Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi. I'm trying to create a batch program that displays a random thought of the day everytime I turn on my computer. The only part of the program I can't figure out is how to select a random thought. I have multiple .txt files in a directory (C:\thoughts). How do I get a batch file to randomly select one of those files and echo its contents?

XP has a built-in RANDOM var so if your files are numbered, let's say, 10 to 99 you can use:
echo type C:\thoughts\%random:~-2%.txt
=====================================
If at first you don't succeed, you're about average.M2

Thanks M2, but that wasn't exactly what I was looking for. I wanted a file that didn't require me to number the filenames, or make sure that I have a certain amount. After much sitting and thinking, I finally came up with a suitable solution
==DisplayRandomFile.bat==
@ECHO OFF
IF EXIST Files.txt DEL Files.txt
IF EXIST OutFile.txt DEL OutFile.txt
FOR /F %%F IN ('"DIR /B *.txt | FIND /V /C "::""') DO SET /A Number=(%Random% %%%%F)
SET DONE==N
IF %Number%==0 GOTO No_Skip
FOR /F "SKIP=%Number%" %%D IN ('"DIR /B *.txt | FIND /V "::""') DO ECHO %%D >>Files.txt
FOR /F "TOKENS=*" %%L IN (Files.txt) DO CALL :1 %%L
GOTO Next
:1
IF %DONE%==Y GOTO :eof
ECHO %*>OutFile.txt
SET DONE=Y
GOTO :eof
:No_SkipFOR /F %%D IN ('"DIR /B *.txt | FIND /V "::""') DO ECHO %%D>>Files.txt
FOR /F "TOKENS=*" %%L IN (Files.txt) DO CALL :2 %%L
GOTO Next
:2
IF %DONE%==Y GOTO :eof
ECHO %*>OutFile.txt
SET DONE=Y
GOTO :eof
:Next
FOR /F %%Z IN (OutFile.txt) DO SET File=%%Z
ECHO TYPE C:\Thoughts\%File%
IF EXIST OutFile.txt DEL OutFile.txt
IF EXIST Files.txt DEL Files.txt
==DisplayRandomFile.bat==
Credit for the part of the script that gets the 1st line from the file "Files.txt" goes to M2 from his solution to one of my previous problems.

Hi CWoodward,
Good work. I'll study your code. Here's what I came up with. It's got some rough edges but it 'works'. Thanks for the kind remarks.
::== randtxt.bat
@echo off
setLocal EnableDelayedExpansionfor /f %%A in ('dir /b c:\thoughts\*.txt^|find /v /c "\"') do set C=%%A
:loop
set R=!random:~-1!
if !R! gtr !C! goto :loop
if !R! equ 0 goto :loop
for /f "tokens=*" %%A in ('dir /b c:\thoughts\*.txt') do (
set /a N+=1
if !N! equ !R! echo type %%A && goto :eof
)
goto :eof
:: DONE
=====================================
If at first you don't succeed, you're about average.M2

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |