user2131714
user2131714

Reputation: 11

Searching string in a multiline file using perl

I'm trying to find a match in a multi-line string using this script. It works only when there's one row in the destination file. I would like to know if there's any substitution for $_ in order to search a multi-line text?

#!/usr/bin/perl

my $time=`date +%D_%H:%M`;
chomp($time);

my $last_location=`cat /file.txt`;
chomp($last_location);

open (ERRORLOG, ">>/errors.log") || die "failed to open errorlog file \n$!\n\a";
open (MESSAGES, "</logfile") || die "failed to open alarms file \n$!\n\a";

seek(MESSAGES, 0, 2) ||  die "Couldn't seek to pos: 0 at end of file $!\n";
$end_position = tell(MESSAGES);

if ($end_position < $last_location) {
    $last_location=0;
}

if ($end_position > $last_location) {
    seek(MESSAGES, $last_location, 0) ||  die "Couldn't seek to pos: $last_location $!    \n";
    $num_of_messages_sent=0;

    while (<MESSAGES>) {
        chomp;
        $line_to_check $_;
        if ($line_to_check =~ /some text/ ) {
            print ERRORLOG "$time: $line_to_check \n";
            if ($num_of_messages_sent < 4) {
                do something;
            }

            if ($num_of_messages_sent == 4) {
                do something;
            }
            #increase counter
            $num_of_messages_sent = $num_of_messages_sent + 1;
        }
    }

    $last_location = tell(MESSAGES);
#        print "last: $last_location   , end: $end_position  \n";
    `echo $last_location >/file_last_location.txt`;
}
close (ERRORLOG);
close (MESSAGES);

Upvotes: 0

Views: 93

Answers (1)

user1126070
user1126070

Reputation: 5069

Looks better this way:

while (my $line = <MESSAGES>) {
  chomp($line);
  print "line : $line\n";
  if ($line =~ m!your_regexp_here!i){
    print ERRORLOG "$time: $line_to_check \n";
    $num_of_messages_sent++;
    print "\tMATCH\tline: $line\n";
    if ($num_of_messages_sent < 4){
      print "Found $num_of_messages_sent matches\n";
    }
  }
}

Upvotes: 1

Related Questions