How to find and replace text in Vim

:%s

Type :, then s/old/new/, then Enter. That replaces the first old on the current line.

Add g at the end to replace every match on the line. Put % before the s to cover every line. :%s/old/new/g replaces it everywhere.

Worked example

Replace every draft in the file with ready.

:%s/draft/ready/gEnter
Your textVim mode: Normal
Replace every draft in the file with ready. Before: status: draft / draft notes / final draft. After: status: ready / ready notes / final ready.

One u undoes the whole replacement, in every line.

Commands

:s/old/new/
Replace the first match on this line.
:s/old/new/g
Replace every match on this line.
:%s/old/new/g
Replace every match in the file.
:2,3s/old/new/g
Replace on lines 2 to 3 only.
:%s/old/new/gc
Ask before each one. Press y to replace or n to skip.
:%s/\<old\>/new/g
Match whole words only.
u
Undo the whole replacement.

Exceptions

  • The old text is a pattern. A dot matches any character, so :s/1.5/x/ also matches 125. Put a backslash before the dot, 1\.5, to match a dot only.
  • Without the backslash, the dot matches the 2 in 125 first.
  • Without g, only the first match on each line changes, even with %.
  • When only some matches should change, go one at a time. Search, change one match with cgn, then press . for each match you want. See the guide to repeating changes.

Try it

The course practises the careful way. You search, change one match, look at the next one, and repeat only where it belongs.