UNIX in a Nutshell: System V Edition

UNIX in a Nutshell: System V EditionSearch this book
Previous: Reference: rChapter 10
The sed Editor
Next: Reference: t
 

s

[address1[,address2]]s/pattern/replacement/[flags]

Substitute replacement for pattern on each addressed line. If pattern addresses are used, the pattern // represents the last pattern address specified. Any delimiter may be used. Use \ within pattern or replacement to escape the delimiter. The following flags can be specified:

g

Replace all instances of pattern on each addressed line, not just the first instance.

p

Print the line if a successful substitution is done. If several successful substitutions are done, sed prints multiple copies of the line.

w file

Write the line to file if a replacement was done. A maximum of 10 different files can be opened.

n

Replace nth instance of pattern on each addressed line. n is any number in the range 1 to 512, and the default is 1.

Examples

Here are some short, commented scripts:

# Change third and fourth quote to ( and ):
/function/{
s/"/(/3
s/"/)/4
}

# Remove all quotes on a given line:
/Title/s/"//g

# Remove first colon and all quotes; print resulting lines:
s/://p
s/"//gp

# Change first "if" but leave "ifdef" alone:
/ifdef/!s/if/   if/


Previous: Reference: rUNIX in a Nutshell: System V EditionNext: Reference: t
Reference: rBook IndexReference: t

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