How to display a random line from a text file?

Solution 1:

You can use shuf utility to print random lines from file

$ shuf -n 1 filename

-n : number of lines to print

Examples:

$ shuf -n 1 /etc/passwd

git:x:998:998:git daemon user:/:/bin/bash

$ shuf -n 2 /etc/passwd

avahi:x:84:84:avahi:/:/bin/false
daemon:x:2:2:daemon:/sbin:/bin/false

Solution 2:

You can also use sort command to get random line from the file.

sort -R filename | head -n1