#!/usr/bin/perl use strict; my (%count, $occ); my @files = ("file1", "file2", "file3"); # read all files sequentially foreach my $file (@files) { open (IN, "<$file") || die "could not open $file\n"; while () { chomp; # if line contains specified string add it to 'file' and 'found string' specific array /(H\(\d+\))/ && do { push @{$count{$file}{$1}}, $_ } } close (IN); } # loop over files foreach my $file (keys %count) { print "$file\n"; # loop over found strings foreach my $found (keys %{$count{$file}}) { # count occurences $occ = scalar (@{$count{$file}{$found}}); # print found lines if occured more than 1 time if ($occ > 1) { foreach (@{$count{$file}{$found}}) { print "$_\n"; } } } print "\n"; } #### file1: N(8) -- H(15) .. O(9) N(8) -- H(16) .. N(8) N(8) -- H(16) .. O(9) file2: N(8) -- H(15) .. O(9) N(8) -- H(15) .. N(8) N(8) -- H(16) .. O(9) file3: N(8) -- H(15) .. O(9) N(8) -- H(15) .. N(8) N(8) -- H(16) .. O(9) #### file1 N(8) -- H(16) .. N(8) N(8) -- H(16) .. O(9) file2 N(8) -- H(15) .. O(9) N(8) -- H(15) .. N(8) file3 N(8) -- H(15) .. O(9) N(8) -- H(15) .. N(8)