Freeman
Freeman

Reputation: 7

Perl regex: second pattern match based on the first one

I need to match and extract a line with a pattern1 from a log which should come after the another pattern2 matched line: for example the log has data like this:

00:00:01 Computing CDA.
00:01:10 Trying to open errorLog1.
00:01:12 writing errorLog1.
00:01:13 Trying to open outLog1.
00:01:14 writing outLog1.
00:01:15 Processing Complete!
00:01:16 Validating documents.
00:02:14 Trying to open errorLog2.
00:02:12 writing errorLog2.
00:02:13 Trying to open outLog2.
00:02:14 writing outLog2.
00:02:15 Processing Complete!

I need to compute the time taken (first column) for document validation. So I want to retrieve the line with "Validating document" string and "Processing Complete" string to extract the time and get the difference. It might be an easy one, but I'm not able to figure out the solution.

Upvotes: 0

Views: 120

Answers (2)

Vijay
Vijay

Reputation: 67319

perl -lane '$a=$F[0] if(/Validating documents/);if(/Processing Complete/){print $F[0]-$a}' your_file

i have simply mentioned $F[0]-$a in the code but its not the way the time is calculated.But that is the part where you have work and calculate the time difference.$F[0] holds the time at which processing complete is encountered in the line

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336498

This should work:

if ($subject =~ m/(\d{2}:\d{2}:\d{2}) Validating documents\..*?(\d{2}:\d{2}:\d{2}) Processing Complete!/s) {
    $start = $1;
    $end = $2;
    # Calculating the time difference is left as an exercise :)
}

Upvotes: 1

Related Questions