如果是我,而不是黑客的东西一起或者awk,并且祈祷没有人会将不方便的空格放入我的配置文件中,我会使用Perl和来自CPAN的Apache::Admin::Config库来正确解析和修改配置文件。
例如:
#!/usr/bin/perl
use strict;
use Apache::Admin::Config;
# Parse config (first command line argument is the file name)
# The indent level is used for the output reformatting at the end, not to read
# the existing configuration.
my $conf = new Apache::Admin::Config($ARGV[0], -indent => 2)
or die $Apache::Admin::Config::ERROR;
# Extract all DirectoryMatch sections
my @dirmatch = $conf->section("DirectoryMatch");
# Of those sections:
for my $dm (@dirmatch) {
# Pick those (hopefully the one) that applies to ".*/wp-admin/"
if($dm->value eq '".*/wp-admin/"') {
# In that section, find all deny directives
my @deny_directives = $dm->directive('deny');
# If there are some:
if(@deny_directives) {
# insert allow directive after the last of them
$dm->add_directive('allow' => 'from ip xxx.xxx.xxx.xxx',
-after => $deny_directives[-1]);
} else {
# Otherwise just insert it at the end.
$dm->add_directive('allow' => 'from ip xxx.xxx.xxx.xxx');
}
}
}
# When done, dump the changed config.
# If reformatting is not desired, use dump_raw instead of dump_reformat.
print $conf->dump_reformat;
在一个文件将这个,说foo.pl
,并运行perl foo.pl foo.conf
,其中foo.conf
是您的Apache的配置文件。
请注意,我对您的用例的语义做了一些假设,这些假设可能会或可能不适合100%,可能需要或可能不需要进行一些调整,以便为您完美工作。无论哪种方式,它至少应该给你一个起点和对图书馆如何工作的粗略想法(文档也在链接之后)。
问题:(1)你已经做了什么? (2)需要匹配的块是什么?这是否正是您在您的代码块中发布的完整信件 - 信件?它只是前5行吗? – Andrew
用awk尝试一下:使用应该匹配的行和计数器处理文件时匹配多少个连续行。当所有行都匹配时,重置计数器并添加拒绝字符串。 –
Andrew,1)在这里贴出来,读了一段不太确定如何在块后面sed 2)这是需要匹配的块...... 3)它的所有行 –