Tuesday, October 5, 2010

Read a random line of text from file in Linux

CLI

There are many ways to achieve this, but this is probably the simplest since you most likely already have all the necessary components installed.

On Ubuntu it's the "shuf" command from "coreutils" package. It's original purpose is to shuffle the lines passed to it, or as its description says: "write a random permutation of the input lines to standard output". However, with one of the arguments you can limit the number of lines it returns, so if all you need is a single line from a given text file, juts run:

$ shuf –n 1 list.txt

where argument –n tells shuf to print only one random line from file list.txt