Yetimwork Beyene
Yetimwork Beyene

Reputation: 2337

How to capture a certain group of lines using perl regex?

How to remove a trailing blank space in a regex substitution?

Here the Data

              __Data__
              Test - results 
              dkdkdkdkdkdkdkdkdkkkdkd
              slsldldldldldldldldldll
              Information
              ddkdkdkeieieieieieieiei
              eieieieieieieieieieieiei
              Test - summary
              dkdkdkdkdkdkdkdkkdkdkdk
              dkdkdkdkdkdkdkdkdkdkdkk

What I would like to remove these lines shown above:

              Information
              ddkdkdkeieieieieieieiei
              eieieieieieieieieieieiei

My attempt using regex expression

           $/ = "__Data__";

           $_ =~ s/^(Test.*[^\n]+)\n(Information.*[^\n]+)\n(Test.*Summary[^\n]+)/$1$3/ms;
              print $_

The input of the data is the same as the output. In other words, nothing changes.

Upvotes: 0

Views: 240

Answers (2)

zortacon
zortacon

Reputation: 627

if you want to remove the information section use

$s =~ s/Information.*Test/Test/s;

if $s contains the data you gave then the following is returned

Test - results 
dkdkdkdkdkdkdkdkdkkkdkd
slsldldldldldldldldldll
Test - summary
dkdkdkdkdkdkdkdkkdkdkdk
dkdkdkdkdkdkdkdkdkdkdkk

If you want the information only then use

$s =~ s/(.*?)(Information.*?)(Test.*)/$2/s;

In both cases notice the the "s" at the end of the substitution, that flag allows it to process multiple lines.

Upvotes: 0

JRFerguson
JRFerguson

Reputation: 7516

Why not this:

while (<DATA>) {
    if ( m/^Information/..m/^Test/ ) {
        next unless m/^Test/;
    }
    s{\s+$}{};
    print "$_\n";
}

Upvotes: 1

Related Questions