How do I run a substitution in Vim without getting an error when the pattern is not found?
Answer
:%s/pattern/replacement/ge
Explanation
The e flag on :substitute silences the "Pattern not found" error that Vim normally reports when a substitution has no matches. This is essential when chaining substitutions in macros, Vimscripts, or bufdo/argdo runs where some files may contain the pattern and others may not.
How it works
- Without
e: if the pattern is not found, Vim reports an error and stops executing further commands in the sequence - With
e: Vim treats a no-match as a success (exit code 0) and continues to the next command - Can be combined with all other flags:
g(all occurrences),i(case-insensitive),c(confirm), etc.
Example
Batch-replace a deprecated function name across all open buffers, ignoring files that don't have it:
:bufdo %s/oldFunction/newFunction/ge | update
Without e, the :bufdo chain would halt on the first buffer where oldFunction doesn't exist.
Tips
- Use
ewhenever writing substitutions intended for scripted or batch use, not interactive use - Combine with
:silentto also suppress the substitution count message::silent! %s/foo/bar/ge - The
eflag does NOT hide genuine errors (like invalid patterns) — only "no match" results