Jill448
Jill448

Reputation: 1793

perl : Regex while reading a file

I have an array of files. Each file with few lines of text, out of which I am trying to get few specific strings through regex in perl

use strict;
use warnings;

foreach my $myfile (@myFiles) {
    open my $FILE, '<', $myfile or die $!;
    while ( my $line = <$FILE> ) {
        my ( $project, $value1, $value2 ) = <Reg exp>, $line;
        print "Project : $1 \n";
        print "Value1 :  $2 \n";
        print "Value2 :  $3 \n";
    }
    close(FILE);
}

* File Content *

Checking Project foobar
<few more lines of text here>
Good Files excluding rules:     15 -   5%
Bad Files excluding rules:    270 -  95%

<one more line of text here>
Good Files including rules:     15 -   5%
Bad Files including rules:    272 -  95%
<few more lines of text here>

* Desired Output *

 Project:foobar  
 Value1 : Good Files excluding rules:     15 -   5%
          Bad Files excluding rules:    270 -  95%   
 Value2 : Good Files including rules:     15 -   5%
          Bad Files including rules:    272 -  95%

Upvotes: 0

Views: 96

Answers (2)

Miller
Miller

Reputation: 35198

It is not worth attempting to create a single regex to capture all of your desired values.

Instead just do line by line processing, and create a regex for each type of line that you want to match.

use strict;
use warnings;

my $fh = \*DATA;

my $counter = 0;

while (<$fh>) {
    if (/Checking Project (\w+)/) {
        printf "Project:%s\n", $1;

    } elsif (/^Good Files/) {
        printf "Value%-2s: %s", ++$counter, $_;

    } elsif (/^Bad Files/) {
        printf "       : %s", $_;
    }
}

__DATA__
Checking Project foobar
<few more lines of text here>
Good Files excluding rules:     15 -   5%
Bad Files excluding rules:    270 -  95%

<one more line of text here>
Good Files including rules:     15 -   5%
Bad Files including rules:    272 -  95%
<few more lines of text here>

Outputs:

Project:foobar
Value1 : Good Files excluding rules:     15 -   5%
       : Bad Files excluding rules:    270 -  95%
Value2 : Good Files including rules:     15 -   5%
       : Bad Files including rules:    272 -  95%

Upvotes: 1

Federico Piazza
Federico Piazza

Reputation: 30985

You can use a regex like this:

(good.*|bad.*)

Working demo

enter image description here

Match information

MATCH 1
1.  [54-95] `Good Files excluding rules:     15 -   5%`
MATCH 2
1.  [96-136]    `Bad Files excluding rules:    270 -  95%`
MATCH 3
1.  [167-208]   `Good Files including rules:     15 -   5%`
MATCH 4
1.  [209-249]   `Bad Files including rules:    272 -  95%`

Using above regex, you can capture the lines you need. Then you have to add some logic to generate your desired output.

Upvotes: 1

Related Questions