Learn Vim / How to Find and Replace in Vim (All Occurrences)

How to Find and Replace in Vim (All Occurrences)

The answerRun :%s/old/new/g% means every line, g means every match on each line.

Try it on a real buffer

Replace every instance of “hello” with “goodbye” in one command: :%s/hello/goodbye/g

hello world
say hello to substitution
hello, hello, and hello again
some lines have no greeting at all
one final hello before you go

Canonical solution: :%s/hello/goodbye/g Enter · par: 20 keystrokes (vimgolf rules — every keypress counts).

Why it works

Anatomy of the command — : enters command mode, % means “every line”, s is substitute, /old/new/ is the swap, and g means “all matches on each line”, not just the first.

Variations

KeysWhat it does
:%s/old/new/greplace all occurrences in the file
:%s/old/new/gcsame, but confirm each replacement
:s/old/new/replace the first match on the current line only
:%s/old/new/gicase-insensitive replace

Reading about keystrokes doesn't build keystrokes. Try this in a real vim buffer right now — the “The great goodbye” mission takes about a minute.

Practice free — no signup →

Keep going