Substitute (:s)

The most powerful single command in Vim.

Keys: :s, :%s

:s/pattern/replacement/flags is the workhorse for text transformation. Combine with ranges (% for whole file) and flags (g for global, c for confirm, i for case-insensitive).

Substitute

:s is Vim's find-and-replace. The full form is:

:[range]s/pattern/replacement/flags

Master it and you can rewrite a file in one keystroke.

Form Meaning
:s/foo/bar/ First match on current line
:s/foo/bar/g All matches on current line
:%s/foo/bar/g All matches in whole file
:%s/foo/bar/gc …with confirmation per match
:'<,'>s/foo/bar/g All matches in last visual selection
:5,10s/foo/bar/g Lines 5-10
:.,$s/foo/bar/g Cursor line to EOF
:g/TODO/s/foo/bar/g Only on lines matching TODO

Flags

Flag Effect
g Replace all matches on each line (not just first)
c Confirm each match (y/n/a/q/l)
i Case-insensitive for this command
I Case-sensitive for this command
e Errors suppressed (no "pattern not found")
n Don't substitute β€” just count matches
& Reuse flags from last :s

Replacement magic

In replacement Means
& The whole match
\0 Same as &
\1, \2… Capture groups from \(...\)
\u Uppercase next character
\U Uppercase until \E
\l, \L Lowercase versions
\r Newline (for splitting lines)
~ Reuse previous replacement

Worked example β€” :s/foo/bar/g

Find and replace on the current line.

Step 1 Β·
ex.substitute
Step 2 Β· Type the substitute command.
Type the substitute command.
Step 3 Β· Enter Β· 3 substitutions on this line.
3 substitutions on this line.

Range :%s/.../.../g applies to whole file. With c flag you confirm each.

β–Ά Try this in the simulator

Watch

See also: Ex Ranges, Global ({key::g}) and Vglobal ({key::v}), Pattern Search