Next: Other Commands, Previous: Common Commands, Up: sed Programs
s
CommandThe syntax of the s
(as in substitute) command is
‘s/regexp/replacement/flags’. The /
characters may be uniformly replaced by any other single
character within any given s
command. The /
character (or whatever other character is used in its stead)
can appear in the regexp or replacement
only if it is preceded by a \
character.
The s
command is probably the most important in sed
and has a lot of different options. Its basic concept is simple:
the s
command attempts to match the pattern
space against the supplied regexp; if the match is
successful, then that portion of the pattern
space which was matched is replaced with replacement.
The replacement can contain \
n (n being
a number from 1 to 9, inclusive) references, which refer to
the portion of the match which is contained between the nth
\(
and its matching \)
.
Also, the replacement can contain unescaped &
characters which reference the whole matched portion
of the pattern space.
Finally, as a GNU sed extension, you can include a
special sequence made of a backslash and one of the letters
L
, l
, U
, u
, or E
.
The meaning is as follows:
\L
\U
or \E
is found,
\l
\U
\L
or \E
is found,
\u
\E
\L
or \U
.
To include a literal \
, &
, or newline in the final
replacement, be sure to precede the desired \
, &
,
or newline in the replacement with a \
.
The s
command can be followed by zero or more of the
following flags:
g
Note: the posix standard does not specify what should happen
when you mix the g
and number modifiers,
and currently there is no widely agreed upon meaning
across sed implementations.
For GNU sed, the interaction is defined to be:
ignore matches before the numberth,
and then match and replace all matches from
the numberth on.
p
Note: when both the p
and e
options are specified,
the relative ordering of the two produces very different results.
In general, ep
(evaluate then print) is what you want,
but operating the other way round can be useful for debugging.
For this reason, the current version of GNU sed interprets
specially the presence of p
options both before and after
e
, printing the pattern space before and after evaluation,
while in general flags for the s
command show their
effect just once. This behavior, although documented, might
change in future versions.
w
file-namee
I
i
I
modifier to regular-expression matching is a GNU
extension which makes sed match regexp in a
case-insensitive manner.
M
m
M
modifier to regular-expression matching is a GNU sed
extension which causes ^
and $
to match respectively
(in addition to the normal behavior) the empty string after a newline,
and the empty string before a newline. There are special character
sequences
(\`
and \'
)
which always match the beginning or the end of the buffer.
M
stands for multi-line.