Tip #539   Using sed across multiple lines

Sometimes when using sed you find that you need to match across line endings, this can be achieved by getting sed to match the first line and then pulling a second line into the buffer with the N command.

For example, if we have a file:
$ cat foo
This is a sample hello
world file.

And want to change 'hello world' to 'hello shell-fu' we need to replace across lines. This can be done with the following command:
:~$ cat foo | sed '/hello$/N;s/hello\nworld/hello\nshell-fu/'
This is a sample hello
shell-fu file.

Here sed first looks for lines which end with 'hello' then reads the next line, finally replacing 'hello\nworld' with 'hello\nshell-fu'.

This also has a lot of other uses, for example converting double line spaced files to single:
cat doublespace | sed '/^$/N;s/\n$//g'