Randomizing Lines in a Text File

June 15, 2010 at 11:26:49
Specs: Windows XP
I'm trying to figure out a way to generate a randomized playlist from a directory of files just using batch commands. The directory contains a couple thousand files spread over some subdirectories and the total number of files within the directory changes often.

The hard part for me is the randomization. My thinking was I could output the file list to a text file, count the lines in that text file, assign a number to each line, then randomly pick from those lines and write them to a new file. There should be no duplicates in the final file and no omissions. Also, it needs to be just file path info without any numbering, such as:


Sadly, I am out of my depth when it comes to this stuff. Is it possible to get the kind of randomization I am looking for without other software/tools?

See More: Randomizing Lines in a Text File

Report •

June 15, 2010 at 13:13:10
I'm not real proud of this, but it may get you close to what you
want to do.


SET music_store="\\Media-center\F Drive on MEDIA-CENTER\Music\Studio\*.mp3"

SET /A song_count=0
FOR /F "tokens=* delims=" %%a IN ('DIR /S /B %music_store%') DO (
    SET /A song_count+=1
    SET song_!song_count!="%%a"
SET /A factor=32767/!song_count!

SET /A random_num=%random%/%factor%
IF /I "!random_num!" LEQ "!song_count!" (
SET random_num=
GOTO shuffle

Report •

June 15, 2010 at 14:05:29
Thanks orangeboy, appreciate your help.

I ended up hacking together my own solution. It's not very elegant and takes a while, but it is working perfectly for me.

It creates a temp directory, then looks into my MP3 directory and creates a text file in that temp directory for every mp3 it finds. The contents of the text files are the file paths to the mp3 it is named for. It then adds a random number to the beginning of the name of every text file, which then gets sorted numerically, and from there the contents of each text file are read in (now random) order and the contents dumped to a playlist file. It then deletes the temp directory.

It's probably ugly to you guys, and it takes a minute or two to run, but it meets my needs.

setLocal EnableDelayedExpansion

MD Temp

FOR /F "tokens=* delims= " %%A in ('dir "D:\Mp3\" /s/b') do (
echo %%A >> "Temp\%%~nA.txt"

FOR /f "tokens=1 delims=" %%T in ('dir "Temp"/s/b *.txt') do (
ren "%%T" "!random!%%~nT.txt" )

COPY "Temp\*.txt" Playlist.m3u

RD /s /q Temp

Report •

June 15, 2010 at 14:10:39
You'll probably get some dups and some misses.


@echo off > rand.m3u & setLocal enableDELAYedeXpansion

for /f "tokens=1* delims=[]" %%a in ('dir/b/s/a-d X:\2O\music\*.mp3 ^| find /n /v ""') do (
  set %%a=%%b
  set H=%%a
@echo off > numlist

for /L %%i in (1 1 !H!) do (
  set /a P=!random!%%!H!+1
  >> numlist echo.!P!

for /f "tokens=*" %%a in (numlist) do (
  >> rand.m3u echo.!%%a!

Helping others achieve escape felicity


Report •

Related Solutions

Ask Question