In: , ,
On: 2004 / 01 / 25 Viewed: 46435 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.

CODE:
  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. 1
    lb Germany »
    replied, on 22/Aug/08 at 1:02 pm # :

    There is still a

    HTML:
    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. 2
    procdaemon United States »
    wrote, on 23/Mar/09 at 4:11 pm # :
    CODE:
    1. NB_LINES=$(expr $(wc -l $1 | sed -e 's/ *//' | cut -f1 -d " "))

    would be better as

    CODE:
    1. NB_LINES=`wc -l &lt;$1`

  3. 3
    stfn Germany »
    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.

Leave a Reply

Comment Guidelines or Die

  • HTML: You can use these tags: <a href=""> <em> <i> <b> <strong> <blockquote>
  • Posting code: Post raw code (no <> &lt; etc) within appropriate tags : [php][/php], [css][/css], [html][/html], [js][/js], [sql][/sql], [xml][/xml], or generic [code][code]
  • Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar.
  • Spam: Various spam plugins on patrol. I'll put pins in a Voodoo doll if you spam me.
  • I will mark as Spam test comments, all comments with SEO names (ie "My Cool Online Shop" instead of "Joe") or containing forum-like signatures.

Read more ?

 « Geek code 
 Better update »