How to display a random line from a text file?
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
You can also use sort
command to get random line from the file.
sort -R filename | head -n1
Just for fun, here is a pure bash solution which doesn't use shuf
, sort
, wc
, sed
, head
, tail
or any other external tools.
The only advantage over the shuf
variant is that it's slightly faster, since it's pure bash. On my machine, for a file of 1000 lines the shuf
variant takes about 0.1 seconds, while the following script takes about 0.01 seconds ;) So while shuf
is the easiest and shortest variant, this is faster.
In all honesty I would still go for the shuf
solution, unless high efficiency is an important concern.
#!/bin/bash
FILE=file.txt
# get line count for $FILE (simulate 'wc -l')
lc=0
while read -r line; do
((lc++))
done < $FILE
# get a random number between 1 and $lc
rnd=$RANDOM
let "rnd %= $lc"
((rnd++))
# traverse file and find line number $rnd
i=0
while read -r line; do
((i++))
[ $i -eq $rnd ] && break
done < $FILE
# output random line
printf '%s\n' "$line"