1

I have a program that basically opens and reads the syslog in ubuntu and use a keyword text file to search for specific words in the syslog and have that to be outputted into an output text file. Problem is, it was all going well until I can't seem to get any errors anymore which doesn't really help me as there is a mistake somewhere which makes me not see any output at all. I ran my regex using a perl online testing tool and it works but doesnt seem so when I try to run it on the terminal. I would be glad if someone could help me with this.

Here is my code:

#!usr/bin/perl

use strict;  
use warnings;

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 $line = <$syslogInfo>)
{

    if($line =~ m/[a-zA-Z]\s(\d{1-31})\s(\d{1-24}):(\d{1-59}):(\d{1-59})\s[a-zA-Z]\s($keywordInfo).\ni/)
    {
        open(outputFile, ">>output");

        flock(outputFile, 2);

        print outputFile "$line\n";
    }
}

Edit: Here is a sample of what is in the syslog

Dec 29 22:02:28 osboxes NetworkManager[686]: plen 24 (255.255.255.0)

8
  • 2
    Your regex doesn't look correct at all. For starters, the first element is for one and only one alphabetical character. I would recommend running your regex through an online tester to make sure it works, such as https://regex101.com/.
    – AntonH
    Jan 2, 2016 at 4:46
  • 1
    $keywordInfo is a filehandle... but the rest of your regex is bonkers as well.
    – Matt Jacob
    Jan 2, 2016 at 4:51
  • Also look here to see a regex to check times.
    – AntonH
    Jan 2, 2016 at 4:52
  • @AntonH Thank you very much for that website helped a lot! But another question though since I cannot find it in the book. How do you add a textfile or string into the regex?
    – TheNoob
    Jan 2, 2016 at 5:17
  • 1
    What's 2? Exclusive lock? Use LOCK_EX exported from Fcntl instead.
    – ikegami
    Jan 2, 2016 at 22:59

1 Answer 1

4

You include $keywordInfo in your regex. But $keywordInfo is a filehandle, which means that, when stringified, it will look like "GLOB(0x1819f30)". I suspect that's not the string that you're looking for.

You know how to read data from a filehandle. You're doing that with your other filehandle, $syslogInfo. So you just need to do that with this filehandle too. Something like this:

my $string_to_find = <$keywordInfo>;
chomp $string_to_find;

# Now use $string_to_find in your regex.
1
  • Oh that helped a lot. Got it working now thank you very much Dave!
    – TheNoob
    Jan 2, 2016 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.