procmail
[Top] [All Lists]

Re: multi-line search/store....

1997-01-02 05:25:24
On Mon, 30 Dec 1996 14:49:19 -0800, Chuq Von Rospach
<chuqui(_at_)plaidworks(_dot_)com> wrote:
I'm trying to write a recipe that'll search across multiple lines of a
body, grab the found piece, and store it to a file as a single line
with the newlines removed (or replaced)

In the general case, you'll need to be a bit more specific about what
you want. Any range of lines between two keywords? Or always two
consecutive lines? If the first of the two consecutive lines contains
a keyword and you just want the second line for context, there's a
switch to grep for that: 

:0 bfW:parsed.errors
|egrep "^.*string I want"

    | egrep -A 1 "string I want"

(Notice that the "^.*" at the beginning is redundant.) This will print
the matching line and the next line after that. (This works with GNU
egrep, I don't think this is widely available in other greps.)

If you don't have GNU grep, or need a more general solution, sed can
do it (or awk, or Perl, in increasing order of versatility). 

So, how can I look for "key string", and stuff both lines into a file
on one line? Unfortunately, changing the format of the incoming mail
isn't possible.

Since you want to collapse the matches onto a single line, you'll
probably end up using sed or Perl anyway. Here's a whack at what I
+think+ you want:

    | perl -ne 'if (m/string I want/) { s/\n//; print; $print = 1; next } \
        print if $print; $print = 0'

Here's a commented version of the Perl scriplet: 

    #!/usr/bin/perl -n      # Loop over input, but don't print unless asked to

    if (m/string I want/)   # We have a match, do something --
    {
        s/\n//;      # Get rid of line terminator (will merge with next line)
        print;       # Print this matching line
        $print = 1;  # Remember the fact that we had a match
        next;        # Now skip to next line of input
    }

    print if $print; # Print this line if the previous line matched
    $print = 0;      # Revert to non-printing (i.e. forget that we had a match)

I'm sure you can adapt this to suit your needs with the aid of the
comments. If you'd prefer to do this in sed, it should be perfectly
doable but less extensible. 

           Chuq Von Rospach (chuq(_at_)solutions(_dot_)apple(_dot_)com) 
Software Gnome

Wooo, a live guru! :-)

/* era */

-- 
See <http://www.ling.helsinki.fi/~reriksso/> for mantra, disclaimer, etc.
* If you enjoy getting spam, I'd appreciate it if you'd register yourself
  at the following URL:  <http://www.ling.helsinki.fi/~reriksso/spam.html>

<Prev in Thread] Current Thread [Next in Thread>