Home > All, Linux > Using sed to search and replace contents of next line in a file.

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

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}/\
}" .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}/ will regex search for an IP and replace the match with your updated IP (in this case
  • .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/.*/

Categories: All, Linux
  1. January 30th, 2015 at 02:33 | #1

    That saves me a lot lines of code and brain cells! Thanks!

  2. August 16th, 2015 at 08:01 | #2

    I’m getting the error message: sed: -e expression #1, char 78: unknown option to `s’
    (Running Debian 7.8)

  1. No trackbacks yet.