Reputation: 41
I'm at a loss at trying to find out how to match the keywords in my keywords text which are:
NetworkManager
dhclient
dbus
My code currently looks like this:
#!/usr/bin/perl
use strict;
use warnings;
use File::Compare;
my $syslogFile = 'syslog';
open (my $syslogInfo, '<', $syslogFile) or die "Could not open $syslogFile";
my $keywordFile = 'keyword';
open (my $keywordInfo, '<', $keywordFile) or die "Could not open $keywordFile";
while(my @keywordArray = <$keywordInfo>)
{
print "@keywordArray\n";
}
while(my @syslogLine = <$syslogInfo>)
{
print "@syslogLine\n";
}
and now I am stuck on how to get these 2 text files to work together and get the desired result.
What Im trying to do is to have things in my syslog txt for example:
Dec 27 21:17:52 osboxes rsyslogd: [origin software="rsyslogd" swVersion="8.12.0" x-pid="695" x-info="http://www.rsyslog.com"] rsyslogd was HUPed
Dec 27 21:18:05 osboxes anacron[634]: Job `cron.daily' terminated
Dec 27 21:18:05 osboxes anacron[634]: Normal exit (1 job run)
Dec 27 21:22:29 osboxes NetworkManager[686]: <info> lease time 1800
Dec 27 21:22:29 osboxes NetworkManager[686]: <info> domain name 'localdomain'
To have it matched with the keywords and only print the lines that have the keywords in it so that it will only print:
Dec 27 21:22:29 osboxes NetworkManager[686]: <info> lease time 1800
Dec 27 21:22:29 osboxes NetworkManager[686]: <info> domain name 'localdomain'
I have tried out using IF by doing this:
if(my @syslogLine = (/^[a-zA-Z][a-zA-Z][a-zA-Z]\s(\d\d)\s(\d\d):(\d\d):(\d\d)\s[a-zA-Z]*\s(@keywordArray).*/s))
{
open(outputFile, ">>output");
print outputFile "@syslogLine\n";
}
but this gives me the errors:
Possible unintended of @keywordArray
Global symbol "@keywordArray requires explict package name
Im guessing that perl doesn't like having an array in the regex? I just couldn't get my head around this problem.
Upvotes: 1
Views: 132
Reputation: 242008
The common approach is to build a regex from the keywords, then read the second file and match each line against the keyword:
#!/usr/bin/perl
use warnings;
use strict;
my $keywordFile = 'keyword';
open my $KW, '<', $keywordFile or die "Could not open $keywordFile";
chomp( my @keywords = <$KW> );
my $regex = join '|', map quotemeta, @keywords;
my $syslogFile = 'syslog';
open my $SYS, '<', $syslogFile or die "Could not open $syslogFile";
while(<$SYS>) {
print if /$regex/;
}
Upvotes: 3