Skip to Content
sed & awk, 2nd Edition
book

sed & awk, 2nd Edition

by Dale Dougherty, Arnold Robbins
March 1997
Intermediate to advanced
432 pages
11h 31m
English
O'Reilly Media, Inc.
Content preview from sed & awk, 2nd Edition

Substitution

We have already demonstrated many uses of the substitute command. Let’s look carefully at its syntax:

[address]s/pattern/replacement/flags

where the flags that modify the substitution are:

n

A number (1 to 512) indicating that a replacement should be made for only the nth occurrence of the pattern.

g

Make changes globally on all occurrences in the pattern space. Normally only the first occurrence is replaced.

p

Print the contents of the pattern space.

w file

Write the contents of the pattern space to file.

The substitute command is applied to the lines matching the address. If no address is specified, it is applied to all lines that match the pattern, a regular expression. If a regular expression is supplied as an address, and no pattern is specified, the substitute command matches what is matched by the address. This can be useful when the substitute command is one of multiple commands applied at the same address. For an example, see Section 5.11.1 later in this chapter.

Unlike addresses, which require a slash (/) as a delimiter, the regular expression can be delimited by any character except a newline. Thus, if the pattern contained slashes, you could choose another character, such as an exclamation mark, as the delimiter.

s!/usr/mail!/usr2/mail!

Note that the delimiter appears three times and is required after the replacement. Regardless of which delimiter you use, if it does appear in the regular expression, or in the replacement text, use a backslash (\) to escape ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The AWK Programming Language, 2nd Edition

The AWK Programming Language, 2nd Edition

Alfred V. Aho, Brian W. Kernighan, Peter J. Weinberger

Publisher Resources

ISBN: 1565922255Supplemental ContentErrata Page