vbynagari has asked for the wisdom of the Perl Monks concerning the following question:

How to print a matching line and one line above it?

Can some one share me a quick way to do it?

this is what is in the file:

**start abc

**start adl

**start xyz

File1 processed

File2 processed

**start zxcv

**start wert

File3 processed

File4 processed

and I want the new file to be:

**start xyz

File1 processed

File2 processed

**start wert

File3 processed

File4 processed

your help is appreciated. thanks

  • Comment on How to print a matching line and one line above it?

Replies are listed 'Best First'.
Re: How to print a matching line and one line above it?
by BrowserUk (Patriarch) on Apr 20, 2011 at 00:32 UTC

    As a slightly unweildy one-liner:

    perl -ne"if(/processed/){ print($last),undef($last) if $last; print;}else{$ +last=$_}" junk.dat **start xyz File1 processed File2 processed **start wert File3 processed File4 processed

    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.
      Thanks for your help. I am kinda new to perl. Can you be a bit more specific on the syntax please?

        C:\test>type junk86.pl #! perl -sw use strict; my $last; while( <> ) { if( /processed/ ){ if( $last ) { print( $last ); undef( $last ) } print; } else{ $last = $_; } } C:\test>type junk.dat **start abc **start adl **start xyz File1 processed File2 processed **start zxcv **start wert File3 processed File4 processed C:\test>junk86 junk.dat >junk.new C:\test>type junk.new **start xyz File1 processed File2 processed **start wert File3 processed File4 processed

        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.
Re: How to print a matching line and one line above it?
by locked_user sundialsvc4 (Abbot) on Apr 20, 2011 at 14:27 UTC

    Here’s the basic strategy...

    Initialize a variable (or as the case may be, an array) to catch the last (the last n...) line(s) that have been seen.   When you realize that you are now looking at a matching line, the variable (or array) contains the last line(s) that you saw before that one.

    If the variable is undef (see the function, “defined()”), or if the array is empty, then there were no lines prior to the matching line.