perl regex cisco configuration file print multiple lines
I am looking for a perl regex that would match "vserver foo2" from the ou开发者_如何学编程tput below. However, I want to return the line of the match, and all the following lines up to the "!" I only want to print the config for "vserver foo2"
Thx for the help!Cisco config:
! vserver foo1 description foo virtual 1.1.1.1 tcp www serverfarm foofoo persistent rebalance inservice ! vserver foo2 description foo2 virtual 1.1.1.2 tcp www serverfarm foofoo2 persistent rebalance inservice ! vserver foo3 description foo3 virtual 1.1.1.3 serverfarm foo3 replicate csrp connection persistent rebalance inservice !perl -ne 'print if /^vserver foo2/ .. /^!/' config.txt
Assuming that $content has all the file, then you should do something like:
my ($config) = $content =~ m/\n!\n(vserver foo2[^!]*)/sm;
assuming that you don't have a the '!' somewhere in your configuration.
But a better way to do it, I think, will be to run a loop, and skip the regex: assuming the $fh is the file handle:
my $line;
# cut the leading lines
do {
$line = <$fh>;
chomp $line;
while ($line ne "!");
while ($line = <$fh>) {
chomp $line;
my $found = ($line eq "vserver foo2");
while ($line = <$fh>) {
chomp $line;
break if $line eq "!";
say $line if $found;
}
break if $found;
}
open IN, '<', '1.txt';
while(<IN>) {
if (/^vserver foo2$/) { $found = 1 }
last if (/^!$/ and $found);
print if $found
}
An regular expression to match the string vserver foo2
is easy: /vserver foo2/
.
Perhaps the easiest way to get multiple lines for this problem is to override the input record separator
variable $/
when you load this file, so that every record (everything between the "!"'s) is kept in a single scalar. For example,
local $/ = "!\n";
open my $fh, '<', $cisco_config_file;
my @configurations = <$fh>;
Now each element of @configurations
contains an entire record. To get the matching records, now you just say
my @matching_records = grep { /vserver foo2/ } @configurations;
精彩评论