By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,852 Members | 2,220 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,852 IT Pros & Developers. It's quick & easy.

How to delete a line with pattern matching

P: 5
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
Mar 9 '10 #1
Share this Question
Share on Google+
2 Replies


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

Expand|Select|Wrap|Line Numbers
  1. my $prev = <>;
  2. while (<>) {
  3.     print $prev unless /tool error/;
  4.     $prev = $_;
  5. }
  6. print $prev;
  7.  
Mar 9 '10 #2

P: 3
use the following code

Expand|Select|Wrap|Line Numbers
  1.  
  2. use strict;
  3. use warnings;
  4. open FH,"<file2" or die "can't Open $!\n";
  5. my $line;
  6. my $flag=1;
  7.  while($line=<FH>)
  8.  {
  9.      if($flag == 0)
  10.      {
  11.          print $line;
  12.          next;
  13.      }
  14.      if($line=~/tool error/)
  15.      {
  16.          $flag=0;
  17.          print $line;
  18.      }
  19. }
  20.  
Mar 18 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.