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:
s/TAB/\ /2
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:
/^\.Ah/{ s/\.Ah */\ \ <h1> s/"//g s/$/<h1>\ / }
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
Copyright © 2003 O'Reilly & Associates. All rights reserved.