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

Re: select N random lines in a file



On Sun, Aug 22, 2004 at 09:16:37PM +0100, Thomas Adam wrote:
> On Sun, Aug 22, 2004 at 04:11:39PM -0400, Travis Crump wrote:
>  
> > That only prints one line whenever the second range number is less than 
> > the first[which happens roughly half the time][ignoring the fact that 
> > ./foo should also be $FILE].
> 
> Yeah, it's not perfect, but it was just off the top of my head. You can do all
> of this in perl, awk, etc.  If you can suggest something, do so.
> 
> -- Thomas Adam
> --
Hi Thom,
ok.
-------------------------------------
#!/usr/bin/perl
use strict;
use warnings;

my $lines = 5;
my $file = "/home/kevin/Mail/backup";

# load file in line array (0..N-1), counting lines
my @line;
open (FH,$file);
        my $count=0;
        while (<FH>){
                $line[$count++]=$_;
        }
close(FH);

# generate N random, non-duplicate numbers stored in a hash

sub ran { # 0..N-1
        my $max = shift;
        return int($max * rand());
}

my %out;
my $i=0;
while($i < $lines){
        my $value = ran($count);
        if (not($out{$value})) {
                $out{$value}=1;
                $i++;
                print $line[$value]; #print the line out in RANDOM order
        }
}
------------------
-Kev
~                                                                                                                                                                     

-- 

        (__)
        (oo)
  /------\/
 / |    ||
*  /\---/\
   ~~   ~~
...."Have you mooed today?"...

Attachment: signature.asc
Description: Digital signature


Reply to: