You seemed very close to having it with what you displayed. You could join the chomp()ed terms from ip.txt using the pipe ('|') character, which in the expression acts as an "or" (iirc), thus making it look for any of the options inside. Adding '^(' and ')$' to it appears to prevent it matching an accidental substring (such as '10.10.10.101', when matching for '10.10.10.10').
Below is the code I threw together that appears to meet the criteria you specified, but does not involve slurping the logfile for searching (which could be an issue with a large logfile) nor the use of grep to perform the actual search. Also, addresses are sorted in IP order, and the resulting report can be made more verbose, giving the number of occurrences in a particular file, by setting $verbose non-zero. It is perhaps not the best of code, but at least gives you a starting point to look at.
#!/usr/bin/perl -w
use strict;
# Turn on short or detailed output
my $verbose = 0;
my $logdir = '.';
my $pattern = '_log';
# Get files to process (from original posted code)
opendir( LOGS, $logdir ) or die ("Can't open $logdir: $!\n");
my @logfiles = grep( /$pattern/, readdir(LOGS) );
closedir(LOGS);
# Slurp in addresses and assemble pattern: ^(aaa|bbb|ccc)$
my ($ippattern);
my $ipfilelist = join ( '/', $logdir, 'ip.txt' );
open( IPLIST, $ipfilelist )
or die ("Can't open $ipfilelist: $!\n");
{
my @iplist = <IPLIST>;
chomp(@iplist);
$ippattern = '^(' . join ( '|', @iplist ) . ')$';
}
close(IPLIST);
# Process files, incrementing results in $found{ip}{filename}
my (%found);
foreach my $file ( sort(@logfiles) ) {
my $filename = join ( '/', $logdir, $file );
open( LOG, $filename ) or die ("Can't open $filename: $!\n");
while (<LOG>) {
chomp;
$found{$_}{$filename}++ if (m/$ippattern/);
}
close(LOG);
}
# Display results, looping through first in ip order,
# then filenames in ASCII order
foreach my $j (
sort( {
unpack( "N", pack( "C4", split ( /\D/, $a, 4 ) ) )
<=> unpack( "N",
pack( "C4", split ( /\D/, $b, 4 ) ) )
} keys(%found) )
)
{
foreach my $k ( sort( keys( %{ $found{$j} } ) ) ) {
print $j;
if ($verbose) {
print ' appeared ', $found{$j}{$k}, ' ',
( $found{$j}{$k} > 1 ? 'times' : 'time' ),
' in file ';
}
else {
print ' is in file ';
}
print $k, "\n";
}
}
__END__
#
# Contents of ip.txt, for testing
192.168.1.1
10.10.10.10
4.3.2.1
#
# Contents of file1_log, for testing
1.1.1.1
4.3.2.1
10.20.30.40
192.168.1.1
10.10.10.10
#
# Contents of file2_log, for testing
2.2.2.2
3.3.3.3
10.10.11.11
10.10.10.10
10.10.10.10
10.10.10.10
10.10.10.10
10.10.10.10
10.10.10.10
10.10.10.100
#
# Sample of output, with $verbose = 0
4.3.2.1 is in file ./file1_log
10.10.10.10 is in file ./file1_log
10.10.10.10 is in file ./file2_log
192.168.1.1 is in file ./file1_log
#
# Sample of output, with $verbose = 1
4.3.2.1 appeared 1 time in file ./file1_log
10.10.10.10 appeared 1 time in file ./file1_log
10.10.10.10 appeared 6 times in file ./file2_log
192.168.1.1 appeared 1 time in file ./file1_log
|