I need to search a very large number of html files for several keywords and save the paragraph containing the word(s) (the line before and after will do). I can do it with the following, but it takes a great deal of time. Given that I need to do hundreds of thousands of files, the minute or so that it takes for each one is unacceptable (will take months at this rate):

#!/usr/bin/perl -w use strict; use LWP::Simple; open ("output","> outputfile.txt") || die ("Could not open output file + $!"); my $html = get("http://www.htmladdress.com/file.html") or die "Couldn't fetch the site."; while($html=~ m{(.+\n.+(key\sword1|key\sword2|key\sword3).+\n.+)}gim){ + my $text =$1; $text =~ tr[\n][ ]; print output "$text\n"; } close ("output");

I've made it more simple than it is in practice. Basically, I get the html file and search for the following sequence: a line, a line break, a line with one of my keywords, a line break, and another line. I think it is taking a long time because I've included such a long sequence of characters to search for. If I don't tell it to look for the surrounding lines (i.e., .+\n.+), it is much quicker (seconds versus minutes).

Ideally, I'd like to identify only my keyword and then save the the previous line, the current line(s), and the subsequent line. Anybody know a way to do this that would speed things up? Also, I want to be able to match a phrase across line brakes, so this might complicate things.

Any help would be greatly appreciated!


In reply to FAST way to pull multiple lines around a keyword 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.