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

How do I suppress the 'Pattern not found' error when a substitution has no match?

Answer

:s/pattern/replacement/e

Explanation

The e flag in Vim's :substitute command silently ignores the "E486: Pattern not found" error when the pattern does not match anything. Without e, a non-matching :s command halts a running macro or script. With e, execution continues uninterrupted.

How it works

  • The /e flag is appended after the delimiter of the substitute command: :s/pattern/replacement/e
  • When the pattern is not found, the error is suppressed and the command is a no-op
  • When the pattern is found, it behaves identically to a normal substitution
  • Combine with other flags: /ge to replace all occurrences on the line and suppress errors, /gei for case-insensitive with no-error

Example

Suppose you want to strip a DRAFT: prefix from all lines, but only some lines have it:

DRAFT: Fix the login form
Add unit tests for API
DRAFT: Update documentation

Running :%s/DRAFT: //e produces:

Fix the login form
Add unit tests for API
Update documentation

Without the e flag, Vim would stop on "Add unit tests for API" with an error. With e, all three lines are processed in one pass.

Tips

  • Essential inside macros: if @q runs a substitution across many lines, the e flag prevents it from stopping on lines that don't match
  • Works in batch pipelines: :argdo %s/oldapi/newapi/ge | update safely renames across all files in the argument list even if some files lack the term
  • Combine with :global: :g/^TODO/s/TODO/DONE/e is redundant (:global already filters by pattern) but demonstrates how flags compose
  • To intentionally check whether a match exists, use :s/pattern/replacement/n (count flag) before deciding whether to apply

Next

How do I show both the absolute line number on the current line and relative numbers on all other lines?