In: , ,
On: 2004 / 01 / 25 Viewed: 48261 times
Shorter URL for this post: http://ozh.in/i

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

Shorter URL

Want to share or tweet this post? Please use this short URL: http://ozh.in/i

Metastuff

This entry "Bash Script: Random Line" was posted on 25/01/2004 at 10:12 pm and is tagged with , ,
Watch this discussion : Comments RSS 2.0.

3 Blablas

  1. lb says:

    There is still a

    1. &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 says:
    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 says:

    nice, thanks.

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

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar and sign for a free account
Spam: Various spam plugins may be activated. I'll put pins in a Voodoo doll if you spam me.

Read more ?

 « Geek code 
 Better update »