Print lines between two patterns in a file

Saturday, December 29, 2012 , 0 Comments

I faced this requirement  where I needed to delete some lines from a file based on two patterns(start and end)for which I thought I would use perl:
1 text 
2 start
3 to be deleted
4 to be deleted
5 text to be deleted      
6 to be deleted          
7 end -should be included
8 text 
9 start
10 text to be deleted
11 end -should be included
12 text

below is the script to achieve this:


#!/usr/bin/perl

use strict;
use warnings;

my $num_to_del;
my @data;
my $to_pr=1;

sub create_files() {

        open(MYFILE, 'joinl.txt');
        while (<MYFILE>) {
if(/start/){
  $to_pr=0;
  }
if(/end/){
         $to_pr=1;
}
         if(defined $to_pr && $to_pr>=1){
print $_;   
}
       }
close(MYFILE);
    }
create_files;

0 comments: