Using Sed to Search & replace a line between pattern ranges

Updated on November 28, 2017

Here’s a question from our regular reader Mr. Rajan. He wants to use Sed to search and replace a line between pattern ranges. Well, here’s a question from him.

I have been writing a shell script to automate few tasks on VPS. For instance, I wanted to modify httpd.conf and replace "AllowOverride None" to "AllowOverride All" that’s located within a particular <Directory "/var/www/html">. The idea is to replace only the line within that particular <Directory> block without affecting other <Directory> blocks (actually there are many, but I’m concerned about the block that contains "/var/www/html"). The reason, I wanted to do this is, I had difficulty in configuring Apache to allow Overrides from .htaccess files.

For example: In the below code from httpd.conf file, I need to search for the pattern <Directory "/var/www/html"> and replace AllowOverride None with AllowOverride All located within this directory structure without affecting other directory structure.

<Directory "/var/www/html">
 AllowOverride None
 </Directory>

Please help me.

Using Sed to Search & replace a line between pattern ranges

This seems to be a task for sed, as sed supports pattern ranges in this form:

sed '/startpattern/,/endpattern/ <sed-commands>' file

So as per the Rajan’s requirement, we need to search for starting pattern <Directory "/var/www/html">, ending pattern </Directory> and find "AllowOverride None" and replace it with "AllowOverride all". To do that, the sed command should be used as shown below.

#sed -i '/<Directory "\/var\/www\/html">/,/<\/Directory>/ s/AllowOverride None/AllowOverride all/' httpd.conf

Here -i option is to edit files in place. If you don’t use the option -i, then the modified output will be printed on the stdout and the file wouldn’t be changed!

Was this article helpful?

Related Articles

Leave a Comment