How to delete a line with pattern matching

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • briggs
    New Member
    • Dec 2009
    • 5

    How to delete a line with pattern matching

    Hi All,
    I have a file which the following data

    This is a sample
    tool error
    end of file

    I need to delete the line before tool error. I can read the file line by line and match for the key word " tool error", but not sure how to delete the line before the matched line.
    Any pointers to solve this?, thnaks in advance
  • toolic
    Recognized Expert New Member
    • Sep 2009
    • 70

    #2
    Keep a copy of the previous line, then only print the previous line if the match of the current line does not succeed (UNTESTED):

    Code:
    my $prev = <>;
    while (<>) {
        print $prev unless /tool error/;
        $prev = $_;
    }
    print $prev;

    Comment

    • murugaperumal
      New Member
      • Mar 2010
      • 3

      #3
      use the following code

      Code:
       
      use strict;
      use warnings;
      open FH,"<file2" or die "can't Open $!\n";
      my $line;
      my $flag=1;
       while($line=<FH>)
       {
           if($flag == 0)
           {
               print $line;
               next;
           }
           if($line=~/tool error/)
           {
               $flag=0;
               print $line;
           }
      }

      Comment

      Working...