Sean Easter
Sean Easter

Reputation: 879

Using perl, how do we print lines between two patterns, skipping first match?

As a motivating example, say we have a document with titled sections, and we want to extract a section using its name and the name of the following section. We could do that with a perl one-liner like this one:

perl -ne 'print if /^<SECTION-NAME-1>$$/ .. /^<SECTION-NAME-2>$$/'

Now, say our document has a table of contents which lists the same sections, and we wish to ignore the first matches of both of these. How would one do this in perl?

Example input:

<SECTION-NAME-1>
we do not care what is here
<SECTION-NAME-2>
or here
<SECTION-NAME-1>
this is the magic stuff
that we would like to extract
<SECTION-NAME-2>
do not need this either

Desired out:

<SECTION-NAME-1>
this is the magic stuff
that we would like to extract
<SECTION-NAME-2>

Output of above one-liner, which mistakenly includes the top portion:

<SECTION-NAME-1>
we do not care what is here
<SECTION-NAME-2>
<SECTION-NAME-1>
this is the magic stuff
that we would like to extract
<SECTION-NAME-2>

Upvotes: 1

Views: 128

Answers (1)

ikegami
ikegami

Reputation: 386676

We could keep using ...

perl -ne'
   next if !( my $ff = /^<SECTION-NAME-1>$/ .. /^<SECTION-NAME-2>$/ );
   print if $skipped;
   $skipped = 1 if $ff =~ /E/;
'

But that complicates things without advantage.

perl -ne'
   next if !( $in ||= /^<SECTION-NAME-1>$/ );
   print if $skipped;
   $skipped = 1, $in = 0 if /^<SECTION-NAME-2>$/;
'

Upvotes: 2

Related Questions