The following code builds two 42 MByte test files (2 million lines each) then runs the analysis. The analysis phase takes about three minutes to run.

#!/usr/bin/perl use strict; use warnings; my $kTestLines = 2000000; my $kMinSame = 2; my $testA = 'testA.txt'; my $testB = 'testB.txt'; srand (1); buildTestFile($_) for $testA, $testB; open my $inA, '<', $testA or die "Can't open $testA: $!\n"; open my $inB, '<', $testB or die "Can't open $testB: $!\n"; my %aKeys; print scalar localtime, "\n"; while (my $aLine = <$inA>) { chomp $aLine; my @keys = map {lc} split /\s+/, $aLine; push @{$aKeys{$_}}, $. for @keys; } while (my $bLine = <$inB>) { chomp $bLine; my @bWords = map {lc} split (/\s/, $bLine); my %lineAHits; ++$lineAHits{$_} for map {@{$aKeys{$_}}} grep {exists $aKeys{$_}} +@bWords; my @matchALines = grep {+$lineAHits{$_} >= $kMinSame} keys %lineAH +its; next if !@matchALines; printf "%s:\n %s\n", join (', ', @matchALines), $bLine; } print scalar localtime, "\n"; sub buildTestFile { my ($fName) = @_; open my $fOut, '>', $fName or die "Can't create '$fName': $!\n"; for (1 .. $kTestLines) { my %words = map {$_ => undef} map { join '', map {randLetter()} 1 .. 4 } 1 .. 4; print $fOut join (' ', keys %words), "\n"; } } sub randLetter { return chr 65 + rand 26; }

Prints (with about 2800 lines omitted):

Sat Feb 27 11:43:38 2016 704856: CYXG GWVB OYLX YNWJ 849378: ECML DIYS APPF OYLR ... 1090468: VSIR CKVJ GWIV IOXN 1327692: YJOQ YOJT NCZL VCSA 740815: ZZJN WYVG EETN QADD Sat Feb 27 11:47:08 2016
Premature optimization is the root of all job security

In reply to Re: compare two text file line by line, how to optimise by GrandFather
in thread compare two text file line by line, how to optimise by thespirit

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.