使用 Perl 中的 RegEx 从设备配置文件中删除部分
Removing a part from a device configuration file using RegEx In Perl
我正在做一个 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
我想删除配置中所有类似的行。
这会过滤掉匹配的行
perl -ne 'if (!/^aaa|enable passwords/) { print $_}'
config_file_name
同样可以通过 grep 命令行完成
grep -v -E '^aaa|enable passwords'
config_file_name
您可以使用以下正则表达式将行替换为空字符串。
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 *******
我正在做一个 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
我想删除配置中所有类似的行。
这会过滤掉匹配的行
perl -ne 'if (!/^aaa|enable passwords/) { print $_}'
config_file_name
同样可以通过 grep 命令行完成
grep -v -E '^aaa|enable passwords'
config_file_name
您可以使用以下正则表达式将行替换为空字符串。
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 *******