简体   繁体   中英

Remove multiple lines between pattern

I am playing with a Cisco config file trying to substitute several things. The way I have been dealing with it is as shown in the snippet below. This works fine for single line substitutions but I can't find a good way to substitute multiple lines in the same block.

(open FILE, $config) || die "Could not open ".$config."\n";
while(<FILE>)
{
   my $line = $_;
   chomp($line);
   if $line =~ (/<someregex>/) {$line =~ s/(<someregex)/;}
   ..
   $conf .= " $line\n";
}
close FILE;

This works for the stuff I've replaces so far (snmp communitites and whatnot). I am now trying to remove the certificates.

For the following example it does not work, probably because it's multiline?

 certificate self-signed 01
  AB238019 01293012 41312309 AF393100 300D484H D32309HF GE349013 50023020
  A6900000 01000000 617FF57F 7A4DB56E 81890281 80301D06 4EF6C8D3 AE00DEDE
  .. etc (total 18 lines)
        quit
!  

The regex I've been playing with is:

if ($line =~ /certificate self.*/) { $line =~ s/(certificate self.*(.+?).*quit)/$2 <withheld-info>/gis;}

Any suggestions as to how this can work?

You can nest while(<FD>) loops. In the outer loop you search for the start sequence and the inner loop you search for the end sequence.

#! /usr/bin/perl

use strict;
use warnings;

LINE: while(<DATA>)
{
   my $line = $_;
   chomp($line);
   if ($line =~ /^ certificate self-signed 01$/)
   {
     while (<DATA>)
     {
       next LINE if /^!$/;
     }
   }
   print $line, "\n";
}

__DATA__
a
 certificate self-signed 01
  AB238019 01293012 41312309 AF393100 300D484H D32309HF GE349013 50023020
  A6900000 01000000 617FF57F 7A4DB56E 81890281 80301D06 4EF6C8D3 AE00DEDE
  .. etc (total 18 lines)
        quit
!
b

The question is not very well articulated, no desired output provided

use strict;
use warnings;
use feature 'say';

my $config = shift or die 'Profile filename';

open my $fh, '<', $config
    or die "Couldn't open $config";
    
my $data = do{ local $/; <$fh> };

close $fh;

$data =~ s/(certificate self-(.+?)quit)/$2 <withheld-info>/gis;

say $data;

Input data file

data #1
data #2
data #3
certificate self-signed 01
  AB238019 01293012 41312309 AF393100 300D484H D32309HF GE349013 50023020
  A6900000 01000000 617FF57F 7A4DB56E 81890281 80301D06 4EF6C8D3 AE00DEDE
  .. etc (total 18 lines)
        quit
!
data #4
data #5
data #6

Output

data #1
data #2
data #3
signed 01
  AB238019 01293012 41312309 AF393100 300D484H D32309HF GE349013 50023020
  A6900000 01000000 617FF57F 7A4DB56E 81890281 80301D06 4EF6C8D3 AE00DEDE
  .. etc (total 18 lines)
         <withheld-info>
!
data #4
data #5
data #6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM