场景:尝试使用sed修改httpd配置文件的大部分内容。
我尝试了什么:
read -d '' _OLD <<"EOF"
<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.2/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
EOF
read -d '' _NEW <<"EOF"
<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.2/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 All
EOF
echo -n ${_OLD}
echo -n ${_NEW}
sed -i "s/$_OLD/$_NEW/g" /etc/httpd/conf/httpd.conf
如果您注意到唯一改变的是AllowOverride All
我只想修改/var/www/html
的规则而不是其他实例的规则,因此我为什么要查看整个块。
我知道可能有更好的方法去做我想要完成的事情。方向将非常感激。
答案 0 :(得分:2)
sed -r '\%<Directory "/var/www/html">%,\%</Directory>% s%(AllowOverride)\s+None%\1 All%i'
答案 1 :(得分:1)
好吧,sed
的我的(过时)版本不允许使用多行'旧'模式(正则表达式),并且需要多行替换才能在换行符之前使用反斜杠,如在
sed "s/lifetime/birth\
…\
death/"
......所以这是一两个问题。另一个是你使用/
作为分隔符,即使你的模式和替换中有斜杠。
我建议您使用正则表达式地址:
sed '/<Directory "\/var\/www\/html">/,/AllowOverride/s/AllowOverride None/AllowOverride All/'
在其他字样中,在 s/AllowOverride None/AllowOverride All/
行之间的任何适用行上执行<Directory "/var/www/html">
替换
以及下一个 AllowOverride
行。
(注意第一个正则表达式中的引号。)
答案 2 :(得分:0)
为什么不使用正则表达式? Sed原生支持它们。 More details here