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
Shorter URL
Want to share or tweet this post? Please use this short URL: http://ozh.in/i

replied, on 22/Aug/08 at 1:02 pm # :
There is still a
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
wrote, on 23/Mar/09 at 4:11 pm # :
would be better as
said, on 02/Nov/09 at 12:50 am # :
nice, thanks.
i use it to open a random website in firefox drawn from a text file.