Apacheの設定で特定のディレクティブ内の一部分のみをsedコマンドで書き換える

Apacheの設定ファイル(httpd.conf)中の<Directory "/usr/local/apache2/htdocs">ディレクティブ内のAllowOverride NoneAllowOverride Allにsedを使って書き換えたい

Apache 2.4.54 をソースからインストールした時のhttpd.confをAllowOverride Noneで検索すると

$ grep "AllowOverride None" -A 5 -B 5  httpd.conf
    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
--
#
# "/usr/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/usr/local/apache2/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule headers_module>

と、AllowOverride Noneが同じ形で2か所あるため単純に

$ sed -i "s/AllowOverride None/AllowOverride All/" /usr/local/apache2/conf/httpd.conf

を行うと

$ grep "AllowOverride All" -A 5 -B 5  httpd.conf
    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
--
#
# "/usr/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/usr/local/apache2/cgi-bin">
    AllowOverride All
    Options None
    Require all granted
</Directory>

<IfModule headers_module>

となり、AllowOverride Noneの部分がすべてAllowOverride Allに変わる

1つ目のAllowOverride None<Directory "/usr/local/apache2/htdocs">ディレクティブ内、2つめのAllowOverride None<Directory "/usr/local/apache2/cgi-bin">ディレクティブ内にあるため、 <Directory "/usr/local/apache2/htdocs">ディレクティブのAllowOverride NoneAllowOverride Allに置換するをsedで表現できればよい

そこで、linux – Using sed to enable .htaccess files in Apache config – Super Userより、

sed -i '/範囲開始行のパターン/,/範囲終了行のパターン/ 範囲に対するコマンド' file

がsedコマンドで利用できるので

sed -i '/<Directory "\/usr\/local\/apache2\/htdocs">/,/<\/Directory>/ s/AllowOverride None/AllowOverride All/' httpd.conf

とすることで

$ grep "AllowOverride All" -A 5 -B 5  httpd.conf
    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
$ grep "AllowOverride None" -A 5 -B 5  httpd.conf
#
# "/usr/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/usr/local/apache2/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule headers_module>

と切り分けた上で置換できた