简体   繁体   中英

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%

You can use a regex like this:

(good.*|bad.*)

Working demo

在此处输入图片说明

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.

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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM