home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Unix Power ToolsUnix Power ToolsSearch this book

34.9. Newlines in a sed Replacement

The backslash (\) in the replacement string of the sed substitution command is generally used to escape other metacharacters, but it is also used to include a newline in a replacement string.

Given the following input line where each item is separated by a tab:

Column1     Column2    Column3     Column4

we can replace the second tab character on each line with a newline character:

2 Section 34.12


Note that no spaces are permitted after the backslash. This script produces the following result:

Column1     Column2
Column3     Column4

Another example comes from the conversion of a file for troff to HTML. It converts the following line for troff:

.Ah "Major Heading"

to a similar line for HTML:

<h1>Major Heading</h1>

The twist in this problem is that the line needs to be preceded and followed by a blank line. It is an example of writing a multiline replacement string:

s/\.Ah */\

The first substitute command replaces .Ah with two newlines and <h1>. Each backslash at the end of the line is necessary to escape the newline. The second substitution removes the quotation marks. The last command matches the end of line in the pattern space (not the embedded newlines) and adds a close h1 tag and a newline after it.

-- DD

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.