start page | rating of books | rating of authors | reviews | copyrights

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 34.7 Delimiting a Regular Expression Chapter 34
The sed Stream Editor
Next: 34.9 Referencing the Search String in a Replacement
 

34.8 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 
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 an ASCII input format for Ventura Publisher(TM). It converts the following line for troff:

.Ah "Major Heading"

to a similar line for Ventura:

@A HEAD = Major Heading

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 */\
\
@A HEAD = /
s/"//g
s/$/\
/    
}

The first substitute command replaces .Ah with two newlines and @A HEAD = . 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 newline after it.

- DD from O'Reilly & Associates' sed & awk, Chapter 5


Previous: 34.7 Delimiting a Regular Expression UNIX Power ToolsNext: 34.9 Referencing the Search String in a Replacement
34.7 Delimiting a Regular Expression Book Index34.9 Referencing the Search String in a Replacement

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System