Skip to main content

How to Shuffle Lines in a Text File Randomly in Batch Script

Shuffling the lines of a text file into a random order is useful for several administrative and creative tasks: creating randomized password lists from a dictionary, shuffling a list of servers to distribute load testing, or even building a simple raffle selection script. While Batch is not built for statistical randomness, we can use the %RANDOM% variable to tag each line and then sort by that tag.

In this guide, we will demonstrate how to perform a shuffle sort in a Batch script.

The Strategy: The Randomized Tag

Since we cannot tell the sort command to be "random," we have to:

  1. Read each line of the source file.
  2. Generate a random number for that line.
  3. Prepend the random number to the start of the line (e.g., 12674|John Doe).
  4. Sort the entire file (the random numbers will now determine the order).
  5. Strip the numbers off the front of the lines, leaving the original text in a new random order.

Implementation Script

@echo off
setlocal disabledelayedexpansion

set "source=List.txt"
set "dest=ShuffledList.txt"
set "temp=%TEMP%\shuf_tagged_%RANDOM%.txt"

:: Verify source file exists
if not exist "%source%" (
echo [ERROR] Source file "%source%" not found.
pause
exit /b 1
)

echo Shuffling "%source%"...

:: 1. Add a zero-padded random tag to the start of every line
:: Pipe delimiter avoids conflicts with colons in URLs or timestamps
(
for /f "usebackq delims=" %%A in ("%source%") do (
set "line=%%A"
setlocal enabledelayedexpansion
set "tag=00000!random!"
echo !tag:~-5!^|!line!
endlocal
)
) > "%temp%"

:: 2. Sort the tagged file, then strip the tags
:: tokens=1* with delims=| separates the tag from the original content
(
for /f "usebackq tokens=1* delims=|" %%a in (`sort "%temp%"`) do (
echo(%%b
)
) > "%dest%"

:: 3. Clean up temp file
del "%temp%" 2>nul

echo [SUCCESS] Shuffled list saved to "%dest%".
pause
exit /b 0

For example, consider the following input file List.txt:

John Doe
Jane Smith
Bob Johnson
Alice Williams

The content of the output file ShuffledList.txt will be:

Alice Williams
John Doe
Jane Smith
Bob Johnson
warning

The for /f loop skips blank lines by design and also skips lines beginning with ; (the default eol character). If your input file contains blank lines or lines starting with ;, those lines will be silently dropped from the shuffled output. The PowerShell method (Method 2) does not have these limitations.

tip

The script uses the delayed expansion toggle pattern: each line is set with delayed expansion disabled (set "line=%%A") to preserve literal ! characters in the file content. It is then read with delayed expansion enabled (echo ... !line!) to safely handle &, |, >, <, and other special characters during output.

Method 2: The PowerShell Shuffle (Higher Randomness)

If you need a more mathematically sound shuffle or if your file is very large, PowerShell provides a faster and more reliable approach.

@echo off
setlocal

set "Source=List.txt"
set "Dest=ShuffledList.txt"

:: Verify source file exists
if not exist "%Source%" (
echo [ERROR] Source file "%Source%" not found.
pause
exit /b 1
)

echo Shuffling "%Source%"...

:: Sort-Object with a random key produces a uniform shuffle
:: This approach works correctly regardless of file size
powershell -NoProfile -Command "Get-Content '%Source%' | Sort-Object { Get-Random } | Set-Content '%Dest%' -Encoding UTF8"

if %errorlevel% equ 0 (
echo [SUCCESS] Shuffled list saved to "%Dest%".
) else (
echo [ERROR] PowerShell shuffle failed.
pause
exit /b 1
)
pause
exit /b 0

For example, consider the following input file List.txt:

John Doe
Jane Smith
Bob Johnson
Alice Williams

The content of the output file ShuffledList.txt will be:

Alice Williams
John Doe
Jane Smith
Bob Johnson

Why Shuffle in Batch?

  1. Load Distribution: If you have 100 servers and 50 people running a script, shuffling the list ensures they do not all target the first 10 servers at the same time.
  2. Privacy: Randomized ordering can help obfuscate sequences in non-critical data processing.
  3. Simulation: For simple games or test harnesses, shuffling inputs provides a varied data set for every run.

Best Practices

  1. Duplicate Random Values: The %RANDOM% variable only returns values from 0 to 32,767. In large files (thousands of lines), multiple lines will receive the same random number. The sort command will group those duplicates together in their original relative order, reducing shuffle quality. The PowerShell method (Method 2) avoids this limitation.
  2. Zero-Pad the Tag: Without padding, sort performs a lexicographic comparison where 9 sorts after 50000 because 9 > 5 as characters. Padding all random values to the same width (e.g., 00042 vs 31507) ensures correct numeric ordering during the sort step.
  3. Choose a Safe Delimiter: If your data contains colons (such as URLs or timestamps), using : as the tag delimiter will corrupt lines during the stripping step. The pipe character (|) is a safer default, but verify that your data does not contain the chosen delimiter. If it does, select another character that does not appear in your data.
  4. Temp File Hygiene: Use the %TEMP% directory for intermediate files and include %RANDOM% in the filename to avoid collisions when multiple instances run simultaneously. Always delete the temp file at the end of the script.
  5. Choose the Right Method: Use Method 1 when PowerShell is unavailable or restricted by policy. Use Method 2 for larger files, higher shuffle quality, or when the input data contains blank lines or semicolons that would be dropped by for /f.

Conclusion

Shuffling a text file is a clever way to add dynamic behavior to your static data sets. By leveraging the "random tag and sort" technique, you can turn a predictable list into a randomized stream of inputs. Whether you use native Batch for simplicity or PowerShell for performance, these methods give you the control necessary to simulate variety and randomness in your automation scripts.