The ex s command takes two arguments, the first being the regular expression that is to be replaced, the second being the replacement.

Command: substitute on lines matching an RE
Usage: [line [,line]] s [[/;]RE[/;]repl[/;] [cgr] [count] [#lp]]

Using \{ and & portions of text can be re-inserted in to the replacement string.

Line    : foo is bar
Command : s/foo\(.*\)bar/\1baz/
New line:  is baz

Line    : foo is bar
Command : s/bar/not &/
New line: foo is not bar
To replace globally within a line, the g operator can be used.
Line    : foo is bar is bar
Command : s/bar/baz/g
New line: foo is baz is baz

To replace all occurrences of bar to baz throughout the entire file, one would use:

Command : 1,$ s/bar/baz/g

The "1" signifies the first line of the file, and the $ the last.

There are many more operations available for use with the s command, consult your ex or vi manual for details.

The s command is also used by other editors like sed, and in programming languages like perl.

QED, a line-oriented texteditor, ancestor to the standard editor: ed. QED was first written in 1967, but the first solid reference I could find to the s command was in QED's manual dated 22 June 1970.


QED Manual (D.M. Ritchie and K.L. Thompson)

S) (.,.) S/<regexp>/<string>/ Substitute.

Occurrences of <regexp> in the addressed lines are replaced by <string>. "." is set to the last line in which a substitution took place. The character "&" in the <string> has a value equal to the text matched by the <regexp>. If a construct of the form "{<regexp2>}x" was used in the <regexp>, the character "x" has value equal to the text matched by <regexp2>.

Any character but space or <nl> may be used instead of "/" to bound the <regexp> If any substitutions took place, the condition register is set to true, otherwise to false. It is not an error for a substitution to fail.

The canonical search and replace operator, as used in sed, Perl, and any other tool that makes use of regular expressions.
s/pattern/replacement/
Any valid regular expression may be sought as pattern. If the s/// operator is followed by g, all occurrences of the pattern are replaced, instead of just the first found; if followed by i, the matching is case-insensitive.

A full discussion of the syntax of s/// is beyond the scope of this writeup, and may be better served by the Perl manual, or the excellent O'Reilly book Mastering Regular Expressions.

The s/// form is often seen in text-based chat environments, where it is used to correct typos in one's previous statements, or humorously in the same manner ^H often is.

Log in or registerto write something here or to contact authors.