Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random selection of lines from a text file

Status
Not open for further replies.

SkyHigh

Technical User
May 30, 2002
309
CA
Hi

I have a text file containing about 700,000 lines and I need to pick 10,000 lines at random, how do I write a script to do this.

Your help will be greatly appreciated

Thanks
Brenda
 
How about this:
Code:
$NumRand = 10000;
$TotLines = 700000;
srand(time ^ $$);
for ($i=0; $i<$NumRand; $i++) {
    do {
        $RandomLine = int(rand($TotLines) + 1);
    } until (! defined $Rand{$RandomLine});
    $Rand{$RandomLine} = 1;
}
open(F, $file) or die &quot;Can't open $file: $!\n&quot;;
open(R, &quot;>$randfile&quot;) or die &quot;Can't open $randfile: $!\n&quot;;
while(<F>) {
    if ($Rand{$.} == 1) {
        print R $_;
    }
}
close(R);
close(F);
 
Thanks, your help is appreciated
Brenda
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top