Substitution

Syntax

  • s/<pattern>/<pattern>/optional-flags
  • <pattern> is a Regex

Parameters

FlagMeaning
&Keep the flags from the previous substitute.
cPrompt to confirm each substitution.
eDo not report errors.
gReplace all occurrences in the line.
iCase-insensitive matching.
ICase-sensitive matching.
nReport the number of matches, do not actually substitute.

Remarks

Use set gdefault to avoid having to specify the 'g' flag on every substitute.

Example

When gdefault is set, running :s/foo/bar on the line foo baz foo will yield bar baz bar instead of bar baz foo.

Keyboard short-cut to replace currenlty highlighted word

For example, with following nmap:

nmap <expr> <S-F6> ':%s/' . @/ . '//gc<LEFT><LEFT><LEFT>'

select a word with *, type Shift-F6, type in a replacement and hit Enter to rename all occurrences interactively.

Quickly refactor the word under the cursor

  1. * on the word you want to substitute.

  2. :%s//replacement/g, leaving the find pattern empty.

Replacement with interactive approval

:s/foo/bar/c Marks the first instance of foo on the line and asks for confirmation for substitution with bar

:%s/foo/bar/gc Marks consecutively every match of foo in the file and asks for confirmation for substitution with bar

Simple replacement

:s/foo/bar Replace the first instance of foo with bar on the current line.

:s/foo/bar/g Replace every instance of foo with bar on the current line.

:%s/foo/bar/g Replace foo with bar throughout the entire file.