Ubuntu – How to display a random line from a text file

scriptstext processing

I am trying to write a shell script. The idea is to select a single line at random from text file and display it as an Ubuntu desktop notification.

But I want different lines to be selected each time I execute the script. Is there any solution to do this? I don't want the entire script. Just that simple thing only.

Best Answer

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