[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: random lines

On Sun, Jul 01, 2001 at 05:15:13PM +0200, Martin F. Krafft wrote:
> hey,
> do you guys know of a smart way to access random lines in a file? so
> if a file had lines 1-5, 5 random reads would return something like
> line3, line1, line2, line5, line4? you get the picture... oh, and that
> preferably in shell-script/awk form?

What exactly is this for?  You could use fortune and strfile.  Make the
text file with a % symbol between each selection, like this:

line 1
line 2
line 3

Then run "strfile <filename>" on the file (every time you make a change
to it), and then you can get a random line from it with "fortune

That's what I do to get randomized quotes in my signature, so if that's
the type of thing you have in mind, I recommend it.

If you don't want to do it the fortune way, you could do it in about one
line of Python after importing the random and linecache modules:

from random import *
from linecache import *
print getline('~/.muttrc',randrange(1,20))

Randrange gives us the random number (between 1 (inclusive) until 20
(not inclusive) in this example), and getline prints the line from, in
this example, my .muttrc.  I assume you'd want to make the particular
file and number of lines variable, but this was just a quickie example.
:)  I don't know as much about shell scripting as I do about Python (and
that's not all that much, either), but I assume you could do it just as
easily; just need something to spit a random number at you, and
something to read a line from a file.

"Take a chance and you may lose. Take not a chance and you have lost
        -Soren Kierkegaard

Reply to: