perl grab part of file after and including search

2020-05-03 10:28发布

问题:

i need to search a file then return contents including, and after a search string. the context is searching a log file where i want to return all messages beginning on a date > the last time stamp. example substring might be: "[Mon Oct 13 20:11:32 2014]".

i have already opened a log file, written it into another file. now i want to reduce the 2nd file to be just the part including and after the substring.

i have seen lots of convoluted regex, etc. and being new to Perl am wondering if it's just me, or is an answer staring me in the face? anything simple, to the point would be much appreciated!

here is what i have so far:

open(FILE, "/opt/workid/logs/error_log") or die "ERROR:cannot open file $!";
open(FILE2, "/opt/workid/logs/output.txt") or die "ERROR:canont open file $!";
if ( /\Q[Mon Oct 13 20:11:32 2014]\E/ ) {
    $var = 1
} if ( $var ) {
    print "/opt/workid/logs/error_log" > "/opt/workid/logs/output.txt"
}

回答1:

One of the problems with your code is this syntax:

print "/opt/workid/logs/error_log" > "/opt/workid/logs/output.txt"

This isn't valid in Perl. You also want to use the 3 argument form of open and lexical filehandles. I put your code into an untested script and made some modifications.

#!/usr/bin/perl
use strict;
use warnings;
open(my $err_fh, '<', "/opt/workid/logs/error_log") or die "ERROR:cannot open file $!"; # open file for reading
open(my $out_fh, '>', "/opt/workid/logs/output.txt") or die "ERROR:cannot open file $!"; # open file for writing
my $var = 0;
while ( <$err_fh> ) { # go through the error log line by line
    if ( /\Q[Mon Oct 13 20:11:32 2014]\E/ ) { # found the timestamp.
        $var = 1;
    }
    if ( $var ) { # print everything after finding the timestamp
        print $out_fh $_;
    }
}

Run with:

perl script.pl

Let me know if there are any problems running this!



回答2:

Here is a pseudo code outline of the approach I would take

open log file for input
open search results file for output
copy_contents = 0

loop over all lines in your log file
   if not copy_contents and time_stamp found
       copy_contents = 1

   if copy_conents
       copy current line to search results file
end loop
close files