Perl REGEX在mac地址上

时间:2014-03-20 22:41:33

标签: regex perl

我通过perl脚本在cisco开关上使用命令“show mac-address-table dynamic”。相同的输出如下:

Legend: * - primary entry
    age - seconds since last seen
    n/a - not available

vlan   mac address     type    learn     age              ports
------+----------------+--------+-----+----------+--------------------------
*   14  782b.cb87.b085   dynamic  Yes          5   Gi4/39
*  400  0017.c59a.23aa   dynamic  Yes         15   Gi3/37
*  400  0017.c59a.23aa   dynamic  Yes          5   Gi1/27
*  400  0017.c50f.704d   dynamic  Yes          5   Gi13/19
*  400  0006.8b05.a915   dynamic  Yes         10   Gi5/29
*  400  c0ea.e414.2f29   dynamic  Yes         10   Gi3/37
*  400  0017.c53e.166d   dynamic  Yes          5   Gi1/12

我正在编写一个脚本,它只取出具有初始前4个数字的mac地址,如0017.c5或0006b或c0ea.e4。此外,它应显示重复的次数。我尝试编写以下代码:

for my $line (@ver) {
    if (my ($mac_addr) = $line =~ /((?:[0-9a-f]{4}\.){2}[0-9a-f]{4})/) {
        $mac_addr = $1;
        if ($mac_addr =~ m/^(0017.c5)[0-9a-f]{2}.[0-9a-f]{4}/ or $mac_addr =~ m/^(c0ea.e5)[0-9a-f]{2}.[0-9a-f]{4}/ or $mac_addr =~ m/^(0006.b)[0-9a-f]{3}.[0-9a-f]{4}/){
            push (@sonic_macaddr, $mac_addr);
            for $it (@sonic_macaddr){
                $uniq{$it}++;
            }
        }
    }
}
print (Dumper(\%uniq));

我没有得到所需的结果。请有人指导我哪里出错了吗?感谢。

2 个答案:

答案 0 :(得分:3)

此匹配将始终失败:

$mac_addr =~ m/^(0017.c5)[.]/

查找所需的前缀,后跟一段时间。你的mac地址都没有第8个字符的句号。

也许以下对脚本的重写会对您有所帮助:

use strict;
use warnings;

my @ver = <DATA>;

my @mac_prefixes = qw(0017.c5 c0ea.e5 0006.b);
my $mac_prefixes = '(?:' . join('|', map quotemeta, @mac_prefixes) . ')';

my @sonic_macaddr;
my %uniq;

for my $line (@ver) {
    if (my ($mac_addr) = $line =~ /((?:[0-9a-f]{4}\.){2}[0-9a-f]{4})/) {
        $mac_addr = $1;
        if ($mac_addr =~ m/^($mac_prefixes)/){
            my $prefix = $1;
            push (@sonic_macaddr, $mac_addr);
            $uniq{$prefix}++;
        }
    }
}

use Data::Dump;
dd \%uniq;
dd \@sonic_macaddr;

__DATA__
Legend: * - primary entry
    age - seconds since last seen
    n/a - not available

vlan   mac address     type    learn     age              ports
------+----------------+--------+-----+----------+--------------------------
*   14  782b.cb87.b085   dynamic  Yes          5   Gi4/39
*  400  0017.c59a.23aa   dynamic  Yes         15   Gi3/37
*  400  0017.c59a.23aa   dynamic  Yes          5   Gi1/27
*  400  0017.c50f.704d   dynamic  Yes          5   Gi13/19
*  400  0006.8b05.a915   dynamic  Yes         10   Gi5/29
*  400  c0ea.e414.2f29   dynamic  Yes         10   Gi3/37
*  400  0017.c53e.166d   dynamic  Yes          5   Gi1/12

答案 1 :(得分:1)

首先你的正则表达式有问题。只需从正则表达式中删除[.]

其次,您将结果推送到@sonic_macaddr数组,然后为每个匹配增加$uniq。它给你错误的数量。所以删除那部分。

以下是修改后if块的外观。

if ($mac_addr =~ m/^(0017.c5)/ or $mac_addr =~ m/^(c0ea.e5)/ or $mac_addr =~ m/^(0006.b)/){
    $uniq{$mac_addr}++;
}

样本数据的输出:

$VAR1 = {
      '0017.c53e.166d' => 1,
      '0017.c59a.23aa' => 2,
      '0017.c50f.704d' => 1
    };