您好我有一个连接到cisco路由器的perl脚本
实际输出如果不像这样分割
show int desc Interface Status Protocol Description Gi1/0/0 up up TRUNK ME-A-JKT-TAN 5/2/1 u/ Service VPN-IP (Support QoS) Gi1/0/0.23 up up VPNIP TIGARAKSA SATRIA BSD,TANGERANG CID 20490023 TENOSS 47086151509200818077
然后我将我的代码放入此脚本中
my @output1 = split(/\s{2,}/, $output);
foreach my $output2 (@output1) {
$output3="$output2%";
my @output4 = split(/\s{2,}/, $output3);
foreach my $output5 (@output4) {
print "$output5#"
}
}
为什么打印出这样的
show int desc Interface%#Status%#Protocol Description Gi1/0/0%#up%#up%#TRUNK ME-A-JKT-TAN 5/2/1 u/ Service VPN-IP (Support QoS) Gi1/0/0.23%#up%#up%#VPNIP TIGARAKSA SATRIA BSD,TANGERANG CID 20490023 TENOSS 47086151509200818077
我希望像这样打印
show int desc#Interface%Status%Protocol%Description#Gi1/0/0%up%up%TRUNK ME-A-JKT-TAN 5/2/1 u/ Service VPN-IP (Support QoS)#Gi1/0/0.23%up%up%VPNIP TIGARAKSA SATRIA BSD,TANGERANG CID 20490023 TENOSS 47086151509200818077#
我想要2个或更多空格,用%分割,/ n用#分割 谢谢你的帮助
答案 0 :(得分:2)
也许是因为你没有chomp
编辑你的台词?此外,您要将#
和%
添加到具有嵌套for
循环的每一行。你的第二个拆分声明与第一个声明相同,是什么让你觉得它什么都没有?
如果您只想替换空格和换行符,为什么不这样做呢?
$output =~ s/\n+/#/g;
$output =~ s/\s{2,}/%/g;
print $output;
此外,您应该知道为变量$output2
,$output3
... $output5
命名是一种可怕的做法。
答案 1 :(得分:1)
有点挑战,但试试这个。它将数据放入哈希数组中。输出为Data::Dumper::Dumper
。将其替换为您选择的格式。
#!/usr/bin/env perl
use strict;
use warnings;
# --------------------------------------
use Data::Dumper;
# Make Data::Dumper pretty
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 1;
# Set maximum depth for Data::Dumper, zero means unlimited
local $Data::Dumper::Maxdepth = 0;
# --------------------------------------
my @Status = ();
my @field_names = ();
my $unpack_template = '';
my $in_body = 0; #TRUE when reading the data
while( my $line = <DATA> ){
chomp $line;
if( $in_body ){
my @fields = unpack( $unpack_template, $line );
# remove trailing spaces
s{ \s+ \z }{}msx for @fields;
# add a hash to the Status
my %status = ();
for my $i ( 0 .. $#field_names ){
$status{ $field_names[$i] } = $fields[$i];
}
push @Status, \%status;
}elsif( $line =~ m{ \A Interface \b }msx ){
# calculate unpack template
while( length $line ){
$line =~ s{ \A (\w+) (\s*) }{}msx;
my $field = $1;
my $spaces = $2;
$unpack_template .= 'a' . ( length( $field ) + length( $spaces ));
push @field_names, $field;
}
# correct the last item to read to end of line
$unpack_template =~ s{ \d+ \z }{*}msx;
# now reading the body
$in_body = 1;
}
}
print Dumper \@Status;
__DATA__
show int desc
Interface Status Protocol Description
Gi1/0/0 up up TRUNK ME-A-JKT-TAN 5/2/1 u/ Service VPN-IP (Support QoS)
Gi1/0/0.23 up up VPNIP TIGARAKSA SATRIA BSD,TANGERANG CID 20490023 TENOSS 47086151509200818077