What's an easy way to read random line from a file in Unix command line? What's an easy way to read random line from a file in Unix command line? unix unix

What's an easy way to read random line from a file in Unix command line?


You can use shuf:

shuf -n 1 $FILE

There is also a utility called rl. In Debian it's in the randomize-lines package that does exactly what you want, though not available in all distros. On its home page it actually recommends the use of shuf instead (which didn't exist when it was created, I believe). shuf is part of the GNU coreutils, rl is not.

rl -c 1 $FILE


Another alternative:

head -$((${RANDOM} % `wc -l < file` + 1)) file | tail -1


sort --random-sort $FILE | head -n 1

(I like the shuf approach above even better though - I didn't even know that existed and I would have never found that tool on my own)