Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sed to replace multiline string?

Tags:

sed

How can I use the bash sed command to change this string:

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

into the following string? (only changing the 3rd line of string)

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

NOTE 1: I don't just want to target the string 'AllowOverride None' because there are other occurrences in the file that should not be changed. I need to target the entire string starting with <Directory /var/www>

NOTE 2: I also need to overwrite the file. So, take that into account in your answer. And provide different versions for GNU/non-GNU versions of sed just in case.

like image 691
eric Avatar asked Jun 14 '16 02:06

eric


People also ask

Can sed replace multiple lines?

Sometimes it requires to replace multiple lines of a file with any particular character or text. Different commands exist in Linux to replace multiple lines of a file. `sed` command is one of them to do this type of task.


1 Answers

Since the patterns contain slashes, use \% (for any character %) to mark the search patterns. Then use:

sed -e '\%^<Directory /var/www/>%,\%^</Directory>% s/AllowOverride None/AllowOverride All/'

The search patterns inside \%…% limit the search to lines between the matching patterns, and the { s/…/…/; } looks for the desired pattern within the range and makes the appropriate replacement.

If you don't want to restrict it to a single directory section but to all directory sections, adjust the start pattern appropriately. For example, this will match any <Directory> section:

sed -e '\%^<Directory [^>]*>%,\%^</Directory>% s/AllowOverride None/AllowOverride All/'

You can make it more selective depending on your requirements.

like image 91
Jonathan Leffler Avatar answered Sep 28 '22 22:09

Jonathan Leffler