You need a sliding buffer--a supersearch for that term will turn up various implementations.

Here's a simple one implemented using an array of lines:

#! perl -slw use strict; my @lines; my %seen; while( <DATA> ) { push @lines, $_; my $buf = join '', @lines; if( $buf =~ /(.{30}these\s+are\s+my\s+keywords.{30})/sm ) { print "'$1'" unless $seen{ $1 }; ++$seen{ $1 }; } shift @lines if @lines > 5; } __END__ Here is my text file I want to save a bunch of charcaters before the keywords for example the keywords might be the phrase: these are my keywords I want to save a bunch of characters after the keywords too so I have context The keywords may appear multiple times in any given file and may span across lines like so: these are my keywords. This is one reason I was using slurp instead of reading in line by line

Which produces:

C:\test>junk 'eywords might be the phrase: these are my keywords I want to save a bunch of ch' 'y span across lines like so: these are my keywords. This is one reason I was u'

You would probably want to make the context at either end optional so you don't miss matches at the start or end of the file where there may not be enough context to match.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

In reply to Re: use regular expressions across multiple lines from a very large input file by BrowserUk
in thread use regular expressions across multiple lines from a very large input file by rizzy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.