Tag Archive "fun"

one-liner to print out a random line from a file

Published May 6th, 2009 by Chad

Here is a bash script one-liner for printing out a random line from a file.

j=$(wc -l words.txt | awk '{print $1}'); i=$RANDOM; i=$(echo "$i%$j+1" | bc); sed -n ${i}p words.txt

The variable j has stored in it the total number of lines in the file with the help of the wc and awk commands. The variable i has stored in it a random number that is then changed to be in between 1 and the number of lines in the file, j. The random number is obtained by assigning i to $RANDOM and then piping a mod operation to the bc calculator. The resulting random line number, i, is displayed using the sed command.

PS: I know the script is on two lines, that that is just because there wasn’t room on the blog to go all the way across.