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.
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.
|<< <||> >>|