Using sed to search and replace contents of next line in a file.
This example will show you how easy it is using sed to find a particular line in a file and replace all or part of the next line. In this example, using htaccess we want to deny access to all clients except a particular dynamic IP (for your home connection for instance).
Your .htaccess file might look like this:
order deny,allow deny from all # allow from example.dyndns.org allow from 8.8.4.4
And your sed code to update the allowed IP address might look like this:
sed -i -r "/# allow from example.dyndns.org/I{\
n; s/([0-9]{1,3}.){3}[0-9]{1,3}/8.8.8.8/\
}" .htaccess
Let’s look at it piece by piece.
- /# allow from example.dyndns.org/I will search the file for this string. The I flag at the end makes the search case insensitive.
- n; will tell sed to continue processing on the next line.
- s/([0-9]{1,3}\.){3}[0-9]{1,3}/8.8.8.8/ will regex search for an IP and replace the match with your updated IP (in this case 8.8.8.8).
- .htaccess is of course the input file to process.
Note that in .htaccess files, comments must be on a line of their own. End of line or inline comments are not permitted. In cases where you do not need to replace a part of the next line but rather all of it, our replacement becomes s/.*/8.8.8.8/

Recent Comments