Return a random line from a file with Bash

18/09/11 | by admin [mail] | Categories: Scripting, Bash, System Programming

I wanted to create a randomised signature generator for my email. I created a file with several different signatures, each on one line, and then used this piece of bashery to take a random line from the file.


head -$((${RANDOM} % $(wc -l < ~/file2.txt) + 1)) ~/file2.txt | tail -1 >> ~/file3.txt

What this does is given a random line from a file (file2.txt) and appends it to another file (file3.txt)
How this does it, is best explained out of order to how it is presented.

First we count the number of in the input file (file2.txt) using wc -l

We feed this in to the RANDOM function of bash as a limit. This means that RANDOM will give us a value within a range between 1 and the number of lines in the file.

We feed this into head, the effect of which is to return the first x lines of the file.

Then use tail to return the last line of this chunk of lines.

The last step directs the output to your output file (file3.txt), and appends it.

Caveats - RANDOM can return zero (hence the +1), RANDOM gives a nominal signed 16bit value (but using the top half 0-32767). So, this might not work well on very large files. RANDOM is pseudo random.


April 2017
Mon Tue Wed Thu Fri Sat Sun
 << <   > >>
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30



XML Feeds

What is RSS?

powered by b2evolution free blog software