vimtricks.wiki Concise Vim tricks, one at a time.

How do I selectively replace occurrences one at a time, choosing to apply or skip each match?

Answer

n.

Explanation

The n. workflow is a powerful alternative to :s///gc for selectively replacing matches. Instead of being prompted for each occurrence, you use Vim's dot-repeat to decide on the fly — press . to apply your last change, or n to skip ahead.

How it works

The technique builds on three primitives:

  • /pattern — set the search register to highlight all matches
  • cgnchange the next match (gn selects the next search match as a text object), dropping you into insert mode
  • . — repeat the last change, which applies the same text replacement to the next highlighted match
  • n — jump to the next match without applying the change (effectively "skip")

The crucial insight is that after a cgn edit, . will:

  1. Jump to the next match (via the embedded gn motion)
  2. Delete it
  3. Insert your replacement text

All in a single keystroke.

Example

foo bar foo baz foo
  1. /foo<CR> — search for foo
  2. cgn then type qux then <Esc> — change first match
  3. . — replace next foo with qux
  4. n — skip the third foo

Result:

qux bar qux baz foo

Tips

  • This is strictly more powerful than :s///gc because your replacement can use any insert-mode editing (paste from register, abbreviations, completion).
  • Start with * instead of /pattern<CR> to instantly search the word under the cursor.
  • Use N. to walk backwards through matches.
  • Combine with :%norm @q when you need the same transformation across many non-contiguous lines.

Next

How do I navigate quickfix entries, buffers, and conflicts with consistent bracket mappings?