Bash: How to Select Random Lines from a File


Often you may want to use Bash to select N random lines from a file.

The easiest way to do so is by using the shuf command to “shuffle” the lines in the file and then by using the -n command to specify how many lines to select from the file.

You can use the following syntax to do so:

shuf -n 5 teams.txt

This particular example selects 5 random lines from the file named teams.txt.

You can also use the > command to save these random lines to a new file:

shuf -n 5 teams.txt > teams_new.txt

This particular example selects 5 random lines from the file named teams.txt and saves the lines to a new file name teams_new.txt.

The following example shows how to use this syntax in practice.

Example: How to Select Random Lines from File Using Bash

Suppose that we have a file named teams.txt in our current directory that contains the names of various basketball teams.

We can use the cat command to first view the contents of this file:

Suppose that we would like to randomly select five lines from this file.

We can use the following syntax to do so:

shuf -n 5 teams.txt

The following screenshot shows how to use this syntax in practice:

Bash select random lines from file

Notice that this returns five random lines from the file.

Note that we could also use the following syntax to select five random lines and then save the lines to a new file named teams_new.txt:

shuf -n 5 teams.txt > teams_new.txt

The following screenshot shows how to use this syntax in practice:

Bash select random lines from file and save to new file

Notice that when we use the cat command to view the contents of the teams_new.txt file we can see that it contains the names of five randomly selected basketball team names.

Note: Feel free to change the number provided after the -n operator to instead randomly select a different number of rows from the file.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Generate Random Number in Range
Bash: How to Check if String Starts with Specific Value
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String

Leave a Reply