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 ...
Get sed & awk, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.