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
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
would be better as
nice, thanks.
i use it to open a random website in firefox drawn from a text file.