8 Substitute command

The substitute command ‘s’ replaces text in the addressed lines matching a regular expression re with replacement. By default, only the first match in each line is replaced. The syntax of the ‘s’ command is:

(.,.)s/re/replacement/[suffixes]

The ‘s’ command accepts any combination of the following optional suffixes:

g

‘global’: replace every match in the line, not just the first.

count

A positive number causes only the countth match to be replaced. ‘g’ and ‘count’ can’t be specified in the same command.

l
n
p

The usual print suffixes. See print suffixes.

I
i

The suffix ‘I’ is a GNU extension which makes ed match re in a case-insensitive manner.

It is an error if no substitutions are performed on any of the addressed lines. The current address is set to the address of the last line on which a substitution occurred. If a line is split, a substitution is considered to have occurred on each of the new lines. If no substitution is performed, the current address is unchanged. The last line modified is copied to the cut buffer.

re and replacement may be delimited by any character other than space, newline, and the characters used by the form of the ‘s’ command shown below. If the last delimiter is omitted, then the last line affected is printed as if the print suffix ‘p’ were specified. The last delimiter can’t be omitted if the ‘s’ command is part of a ‘g’ or ‘v’ command-list and is not the last command in the list, because the meaning of the following escaped newline would become ambiguous.

An unescaped ‘&’ in replacement is replaced by the currently matched text. The character sequence ‘\m’ where m is a number in the range [1,9], is replaced by the mth backreference expression of the matched text. If the corresponding backreference expression does not match, then the character sequence ‘\m’ is replaced by the empty string. If replacement consists of a single ‘%’, then replacement from the last substitution is used.

A line can be split by including a newline escaped with a backslash (‘\’) in replacement. Each backslash in replacement removes the special meaning (if any) of the following character.

ed can repeat the last substitution using the following alternative syntax for the ‘s’ command:

(.,.)s[suffixes]

This form of the ‘s’ command accepts the suffixes ‘g’ and ‘count’ described above, and any combination of the suffixes ‘p’ and ‘r’. The suffix ‘g’ toggles the global suffix of the last substitution and resets count to 1. The suffix ‘p’ toggles the print suffixes of the last substitution. The suffix ‘r’ causes the re of the last search to be used instead of the re of the last substitution (if the search happened after the substitution).