[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?

Did I fail the deadline yet?

perl -e 'print map {$_->[1]} sort {$a->[0]<=>$b->[0]} map {[rand,$_]} <>' file

Unlike some other solutions posted, this is not a "random pick" program,
but a full set permutating one.  It is quite elementary, I bet that it
already exists in some corner of the web/usenet.

The "map sort map" construct is called "the schwartzian transform",
in honor of randall schwartz, gifted co-author of perl, perl books and
many other goodies.

The way I'm using it is to take a list of lines from standard input. Next
a new list of pairs (random_num, input_line) is created from this list.
The list of pairs is then sorted by the first member of each pair.
The sorted list of pairs is then turned into final list, consisting of
only the second member of each pair in the sorted list, while keeping
the sort order of the list of pairs.  The final list is then printed.
Read from right to left.

Cheers,


Joost



Reply to: