To keep track of which file you are reading use the $ARGV variable. See perlop manual page for more information on the powerful <> 'diamond' operator.
Assuming you are dealing with files that can comfortably sit in memory I suggest a simple hash of hash to keep track of which line was seen by which file.
use strict; use warnings; my $file_count=@ARGV; my %seen; while(<>) { # File $ARGV saw line $_ at least once by file $ARGV $seen{$_}{$ARGV}++; } while( my ($line, $by_whom) = each %seen) { if ( $file_count == keys %$by_whom) { # Every file saw this line at least once print $line } }
If you want this as a one-liner you can use the -n flag to wrap a diamond operator around the central loop. This leads to the slightly obfuscated one liner with plenty of scope for golfing
perl -ne 'BEGIN{$count = @ARGV}; $seen{$_}{$ARGV}=1; END{while( ($line +, $by_whom) = each %seen){ print $line if $count == keys %$by_whom}} +'
In reply to Re: find common lines in many files
by amcglinchy
in thread find common lines in many files
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |