Regex Perl多行正则表达式替换捕获组
我在一个Makefile中添加了一行Perl代码,该文件在httpd.conf中搜索类似以下的块,并将AllowOverride的“None”替换为“All”Regex Perl多行正则表达式替换捕获组,regex,perl,Regex,Perl,我在一个Makefile中添加了一行Perl代码,该文件在httpd.conf中搜索类似以下的块,并将AllowOverride的“None”替换为“All” <Directory "/var/www/html"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSym
<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>
#
#选项指令的可能值为“无”、“全部”,
#或以下任何组合:
#索引包括以下符号链接符号链接所有者匹配执行CGI多视图
#
#请注意,“多视图”必须显式命名为*--“所有选项”
#不给你。
#
#期权指令既复杂又重要。请看
# http://httpd.apache.org/docs/2.4/mod/core.html#options
#了解更多信息。
#
选项索引跟随符号链接
#
#AllowOverride控制可在.htaccess文件中放置的指令。
#它可以是“全部”、“无”或关键字的任意组合:
#选项FileInfo AuthConfig限制
#
不允许超限
#
#控制谁可以从此服务器获取内容。
#
要求所有授权
我试图从命令行运行的代码如下:
sudo perl -p -i -e 's/(<Directory "\/var\/www\/html">.*AllowOverride )(None)/\1 All/' httpd.conf
sudo perl-p-i-e的/(.*AllowOverride)(None)/\1 All/'httpd.conf
但是我不能让它工作。我使用两个捕获组来保持第一个组不变并替换第二个组
非常感谢您的帮助
编辑:这解决了它
sudo perl -0777 -p -i -e 's/(<Directory \"\/var\/www\/html\">.*?AllowOverride) (None)/\1 All/s' httpd.conf
sudo perl-0777-p-i-e's/(.*AllowOverride)(None)/\1 All/s'httpd.conf
一般来说,解析和修改任何与正则表达式嵌套的东西都会变得很复杂,而且很容易出错。如果可以,请使用完整的解析器
幸运的是,有一个用于读取和修改Apache配置文件的。一开始有点奇怪,下面是一个例子
#!/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;
默认情况下,
-p
标志一次只能读取一行。通过添加-0777
,尝试一次发出多行的声音。另请参见,请确保使用非贪婪的*?
,否则它将一直匹配到最后一个允许超越
。使用$1
,而不是\1
——或\K
(一种积极的后视形式)。这解决了它:sudo perl-0777-p-i-e的s/(.*AllowOverride)(None)/\1 All/s的httpd.confGreat。同样:不是\1
,而是$1
。\1
长期以来没有用于此功能,虽然它不会给您带来麻烦,但它在regex中用于其他功能。有一个模块,用于读取和编辑Apache配置文件。
for my $section ($config->section("Directory")) {
...
}