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

How do I replace only the current match and then stop when doing an interactive substitution in Vim?

Answer

l (in :%s///gc confirm prompt)

Explanation

When running an interactive substitution with the c flag (e.g., :%s/pattern/replacement/gc), Vim pauses at each match and prompts for confirmation. Most users know y (yes), n (no), a (all remaining), and q (quit). The lesser-known l key means "substitute this match, then stop" — effectively treating the current match as the last one regardless of how many remain.

How it works

During a :%s/pattern/replacement/gc session, Vim shows:

replace with replacement (y/n/a/q/l/^E/^Y)?

The available responses are:

  • y — replace this match, continue to next
  • n — skip this match, continue to next
  • a — replace this and all remaining matches without further prompting
  • q — quit without replacing this match
  • l — replace this match and quit ("last" substitution)
  • <C-e> — scroll up to see more context
  • <C-y> — scroll down to see more context

Example

In a file with three occurrences of foo, running :%s/foo/bar/gc and pressing l at the second match replaces only that occurrence and stops — leaving the third match untouched.

Tips

  • l is mnemonic for "last" — substitute this, and make it the last one
  • Useful when you only need to replace a specific occurrence but don't want to count ahead to use n then a
  • Combine with q in scripts or macros for controlled substitution workflows

Next

How do I open the directory containing the current file in netrw from within Vim?