Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2005
    Posts
    16

    Unanswered: perl print question

    Hello,

    I have numerous files with tons of information in them. Everything stays the same (format wise) each time the file is created. What I want to do is search for a specific word(s) and print the line directly above it into another file. The word(s) I'll be searching for will remain the same every time. The file will look something like this:

    my name is earl (guy)
    say: hello
    good: bye
    etc
    no

    my name is frank (crazy)
    say: goodbye
    hello:
    etc
    yes

    What I want to do is print the first line above every section that has "say: hello" on one line into another file. And get rid of the (* after the line im printing. I don't have any issues finding the "say: hello". I'm having trouble printing the line above "say: hello". Anyone have any ideas as to how I can about printing the line above the keywords i'm looking for?

    Thanks in advance,

    -Hoffa

  2. #2
    Join Date
    Jan 2006
    Posts
    32
    Try something like:
    Code:
       open(INPUT, "< file");
    
       $prev_line = "";
       while ($line = <INPUT>)
         {
          if  (    ($line =~ m/^say hello:/)
               and (length($prev_list) > 0)
              )
            { print "$prev_line\n"; }
    
          $prev_list = $line;
         }


    .

  3. #3
    Join Date
    Feb 2004
    Location
    In front of the computer
    Posts
    15,579
    Provided Answers: 54
    Working along the same lines, but in what I consider more "Perl-ish" fashion I'd suggest:
    Code:
    #  ptp  20060125  Show the line before a line that matches a pattern
    
    $p = <>;
    
    while (<>) {
       if (/^say: hello$/) { print $p };
       $p = $_;
       };
    This eliminates the need to have a corporeal file (it will just as happily read a stream or work within a pipe), it only uses one variable, and makes better use of built in Perl features... It also produces the correct output against the test case presented.

    -PatP

  4. #4
    Join Date
    Jun 2004
    Location
    Nowhere Near You
    Posts
    89
    along Pat's lines: using ping-pong buffers

    note: $i=1-$i oscillates between 0 and 1 if we begin with $i = 0 or $i = 1;
    note: if $a[$i] is the hello line, $a[1-$i] is the previous line.

    Code:
    my($i,@a)=0;
    while ($a[$i=1-$i]=<>) {
       print $a[1-$i] if (a[$i] =~ /^say: hello$/);
        };
    Last edited by senza_nome; 01-26-06 at 23:20.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •