我正在尝试匹配文件中的整个文本块,然后我需要在之后插入一个新行。需要匹配整个块,因为每个行都重复代码中的其他位置
<DirectoryMatch ".*/wp-admin/" >
AllowOverride None
AuthType Basic
AuthName 'Authenticate'
Require valid-user
order deny,allow
deny from all
并在deny语句下方插入allow ip from xxx.xxx.xxx.xxx.xxx
答案 0 :(得分:0)
如果是我,而不是用sed或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 :(得分:0)
awk '{sub(/deny from all/, "deny from all\nallow ip from xxx.xxx.xxx.xxx.xxx")}1' file
<DirectoryMatch ".*/wp-admin/" >
AllowOverride None
AuthType Basic
AuthName 'Authenticate'
Require valid-user
order deny,allow
deny from all
allow ip from xxx.xxx.xxx.xxx.xxx