How to Randomize Lines of Text Using the shuf Command in Linux

When working with massive text datasets in a Linux terminal, you will often need to randomize the order of the data. You might need to shuffle a list of survey participants, randomize the lines in a CSV file to train a machine learning model, or simply pick a random winner from a list of names. While writing a Python script to do this is common, Linux includes a native utility called shuf (shuffle) that can generate perfectly random permutations of lines directly from the command line.

How to Shuffle a Text File

The shuf command is incredibly simple to use. At its most basic, you just pass it the name of a file. It will read the entire file into memory, randomize the order of every single line, and print the resulting chaos to the standard output (your terminal screen).

Imagine you have a file named contestants.txt containing five names:

Alice
Bob
Charlie
David
Eve

If you run the command:

shuf contestants.txt

The output will be completely randomized, for example:

David
Alice
Eve
Bob
Charlie

Because the output goes directly to the terminal, the original contestants.txt file remains completely untouched and perfectly ordered.

How to Select a Random Subset (The “Winner”)

One of the most powerful features of shuf is its ability to not just shuffle a list, but also truncate the output. By using the -n (head count) flag, you can tell the utility to shuffle the entire file but only output the top N results.

If you have a file containing 10,000 email addresses and you want to pick exactly three random winners for a giveaway, you would run:

shuf -n 3 emails.txt

The utility performs a true random shuffle of all 10,000 lines, but stops and prints only the first three results, providing a perfectly randomized subset.

Generating Random Numbers

The shuf command is not limited to reading text files. You can also use it as a powerful random number generator by utilizing the -i (input range) flag. You must provide a low number and a high number separated by a hyphen.

To simulate a six-sided die roll, you want a single random number between 1 and 6. You would combine the input range flag with the head count flag:

shuf -i 1-6 -n 1

The terminal will instantly output a single random integer (e.g., 4).

If you wanted to simulate a lottery draw by picking five unique, non-repeating numbers between 1 and 50, you would run:

shuf -i 1-50 -n 5

The output will display five completely random, distinct numbers, making shuf one of the most versatile scripting tools available in bash.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.