Bash Script: Random Line

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

  1. #!/bin/bash
  2. # randomline : extracts a random line from a text file
  3.  
  4. if [ -z $1 ] ; then
  5. echo "Usage : $0 <file>"
  6. exit 0
  7. fi
  8.  
  9. NB_LINES=$(expr $(wc -l $1 | sed -e 's/ *//' | cut -f1 -d " "))
  10.  
  11. NB_RAND=0
  12. while [ "$NB_RAND" -eq 0 ]
  13. do
  14. NB_RAND=$(expr $RANDOM \% $NB_LINES)
  15. done
  16.  
  17. sed -n "${NB_RAND}p;${NB_RAND}q" $1

3 comments

  1. lb

    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

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

    would be better as

    1. 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.