Bash Script: Random Line

This bash script extracts a random line from a given (text) file. This is a cheap "fortune" replacement.

#!/bin/bash
# randomline : extracts a random line from a text file

if [ -z $1 ] ; then
echo "Usage : $0 <file>"
exit 0
fi

NB_LINES=$(expr $(wc -l $1 | sed -e 's/ *//' | cut -f1 -d " "))

NB_RAND=0
while [ "$NB_RAND" -eq 0 ]
do
NB_RAND=$(expr $RANDOM \% $NB_LINES)
done

sed -n "${NB_RAND}p;${NB_RAND}q" $1

3 comments

  1. lb

    There is still a

    &lt;

    remaining in the plaintext version.

    I am an absolute sh beginner, I use your very helpful script in a small project of mine and will modify it a bit because the call of wc takes its toll.
    I search in a quite large file (5 digit number of lines) and that quite often, so I get a lot of redundancy. (~0.1 seconds for the 4 calls I do.)

    Best

    lb

  2. procdaemon
    NB_LINES=$(expr $(wc -l $1 | sed -e 's/ *//' | cut -f1 -d " "))

    would be better as

    NB_LINES=`wc -l &lt; $1`
  3. stfn

    nice, thanks.

    i use it to open a random website in firefox drawn from a text file.

Comments are closed.