Perl Multiline Regex取代Capture Group

时间:2017-03-14 20:22:02

标签: regex perl

我将一行Perl代码添加到Makefile中,该文件在httpd.conf中搜索类似下面的块,并替换" None"与"所有"对于AllowOverride。

<Directory "/var/www/html">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

我尝试从命令行运行的代码如下:

sudo perl -p  -i -e 's/(<Directory "\/var\/www\/html">.*AllowOverride )(None)/\1 All/' httpd.conf

但我无法让它发挥作用。我使用两个捕获组来保持第一组相同并替换第二组。

非常感谢任何帮助。

编辑:这解决了它

sudo perl -0777 -p -i -e 's/(<Directory \"\/var\/www\/html\">.*?AllowOverride) (None)/\1 All/s' httpd.conf

1 个答案:

答案 0 :(得分:3)

通常,解析和修改嵌套有正则表达式的任何内容都会很快变得复杂,容易出错。如果可以,请使用完整的解析器。

幸运的是,有一个用于读取和修改Apache配置文件的Apache::Admin::Config。一开始有点奇怪,所以这是一个例子。

#!/usr/bin/env perl

use strict;
use warnings;
use v5.10;

use Apache::Admin::Config;

# Load and parse the config file.
my $config = Apache::Admin::Config->new(shift)
    or die $Apache::Admin::Config::ERROR;

# Find the <Directory "/var/www/html"> section
# NOTE: This is a literal match, /var/www/html is different from "/var/www/html".
my $section = $config->section(
    "Directory",
    -value => q["/var/www/html"]
);

# Find the AllowOverride directive inside that section.
my $directive = $section->directive("AllowOverride");

# Change it to All.
$directive->set_value("All");

# Save your changes.
$config->save;

您一次只钻一层结构。首先找到该部分,然后是该指令。

您可以循环执行此操作。例如,找到所有目录部分......

for my $section ($config->section("Directory")) {
    ...
}