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
/eflag 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:
/geto replace all occurrences on the line and suppress errors,/geifor 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
@qruns a substitution across many lines, theeflag prevents it from stopping on lines that don't match - Works in batch pipelines:
:argdo %s/oldapi/newapi/ge | updatesafely renames across all files in the argument list even if some files lack the term - Combine with
:global::g/^TODO/s/TODO/DONE/eis redundant (:globalalready 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