2015-10-20 63 views
-1

我試圖匹配文件中的整個文本塊,然後我需要在後面插入新行。整個區塊需要匹配的每一行與SED重複其他地方的代碼如何匹配整個文本塊並在shell腳本中插入行之後

<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

+0

問題:(1)你已經做了什麼? (2)需要匹配的塊是什麼?這是否正是您在您的代碼塊中發佈的完整信件 - 信件?它只是前5行嗎? – Andrew

+0

用awk嘗試一下:使用應該匹配的行和計數器處理文件時匹配多少個連續行。當所有行都匹配時,重置計數器並添加拒絕字符串。 –

+0

Andrew,1)在這裏貼出來,讀了一段不太確定如何在塊後面sed 2)這是需要匹配的塊...... 3)它的所有行 –

回答

0

如果是我,而不是黑客的東西一起或者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%,可能需要或可能不需要進行一些調整,以便爲您完美工作。無論哪種方式,它至少應該給你一個起點和對圖書館如何工作的粗略想法(文檔也在鏈接之後)。

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 
相關問題