in reply to Indexing two large text files
You can do this in multiple passes by reading a batch of the records from file2 into a hash and then processing file1 against them. Any records from file 1 matched get written to the new file, modified. Any that don't match get written to a spill file.
When you've processed all the records from file1 against the first batch, you then close it; read the next batch from file2; and process the spill file against the new batch. Rinse and repeat until there are no records left in file2. At that point, any records left in the spill file have no matches and can be output to the new file unmodified.
This sounds complex, but actually codes fairly simply. One thing to be aware of is that file1 will be overwritten in the processing. If you need to retain it, copy it first.
UPDATE{ 18:06 GMT }: DO NOT USE! Has a bug! .................
UPDATE{ 18:26 GMT }: BUG FIXED!
Here's the code:
#! perl -slw use strict; our $N //= 1e6; my $file1 = 'file1'; my $spill = 'temp'; open FILE2, '<', 'file2' or die $!; my $done = 0; until( $done ) { ## Index a batch of records from file 2 my %idx; for( 1 .. $N ) { chomp( my @bits = split /\*/, <FILE2> ); $idx{ $bits[ 0 ] } = $bits[ 1 ]; $done = 1, last if eof FILE2; } open FILE1, '<', $file1 or die $!; open SPILL, '>', $spill or die $!; ## process records from file (or spill) file while( <FILE1> ) { chomp( my @bits = split /\*/ ); ## If it exists in this batch, write the modified record to ST +DOUT if( exists $idx{ $bits[ 0 ] } ) { print join '*', $bits[ 0 ], $idx{ $bits[ 0 ] }, $bits[ 2 ] +; } else { ## otherwise put it in the spill file for next pass local $\; print SPILL; } } close SPILL; close FILE1; ## switch the input(file1) and spill file names ( $file1, $spill ) = ( $spill, $file1 ) unless $done; } ## Anything left in the spill file goes through unmodified local $\; open SPILL, '<', $spill; print while <SPILL>; close SPILL; ## Remove the tempories unlink $spill; unlink $file1;
To use it: theScript -N=1e6 > theNewFile. You can adjust -N=1e6 to increase the number of file2 records processed in each pass, thus reducing the number of passes. A 32-bit Perl will probably be able to handle at least 5e6 per pass.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Indexing two large text files
by never_more (Initiate) on Apr 10, 2012 at 11:54 UTC |