【问题标题】:Removing a part from a device configuration file using RegEx In Perl使用 Perl 中的 RegEx 从设备配置文件中删除部件
【发布时间】:2016-02-13 10:53:19
【问题描述】:

我正在做一个 perl 项目。我需要从设备的运行配置中删除一些配置。

在我的后端代码中,我以下面给出的标量形式获取设备配置:

my $node_config = $self->get_node_config($node);

现在,当我在控制台上转储$node_config 的内容时,我得到了运行配置的设备,其中包含一些我想要删除的配置。 我要删除所有'aaa'相关配置和'enable passwords'配置全行。

例如,我有以下方式的配置:

enable secret 3 *******

enable passwords something

aaa authentication login

aaa authentication login

aaa authentication enable

aaa authorization console

aaa authorization config

我想删除配置中所有类似的行。

【问题讨论】:

    标签: regex string perl replace config


    【解决方案1】:

    您可以使用以下正则表达式将行替换为空字符串。

    s/(?:^|\n)(?:enable passwords|aaa) .*//g
    
    • (?:^|\n) 匹配字符串开头或换行符(匹配行开头)。
    • (?:enable passwords|aaa) 两个选项都是文字。
    • .* 该行的其余部分。

    代码

    my $node_config = "
    enable secret 3 *******
    enable passwords something
    aaa authentication login
    aaa authentication login
    aaa authentication enable
    aaa authorization console
    aaa authorization config";
    
    $node_config =~ s/(?:^|\n)(?:enable passwords|aaa) .*//g;
    
    print $node_config;
    

    输出

    enable secret 3 *******
    

    ideone demo

    【讨论】:

    • 非常感谢..!!它就像一个魅力..!! :) 虽然我在想如果我想替换以下行: username ******* secret 5 ******* with username default default 那我该怎么办..!! :)
    • 可能类似于 this,但不清楚您要做什么。如果您无法使用此信息解决问题,请提出一个新问题。
    • 嘿马里亚诺我解决了...!! :) 使用了以下正则表达式:- $node_config =~ s/(?:^|\n)(?:username).*/\nusername default password default/g;
    【解决方案2】:

    这会过滤掉匹配的行

    perl -ne 'if (!/^aaa|enable passwords/) { print $_}' config_file_name

    同样可以通过 grep 命令行来完成

    grep -v -E '^aaa|enable passwords'config_file_name

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多