使用perl在多行文件中搜索字符串

时间:2014-05-19 11:30:19

标签: perl

我尝试使用此脚本在多行字符串中查找匹配项。 它仅在目标文件中有一行时才有效。 我想知道是否有任何替换$ _才能搜索多行文字?

#!/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);

1 个答案:

答案 0 :(得分:1)

这样看起来更好:

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";
    }
  }
}