How do I run a substitution in Vim without getting an error if the pattern is not found?
Answer
:s/pattern/replacement/e
Explanation
The e flag on the :substitute command silently suppresses the E486: Pattern not found error when the pattern has no matches. This is invaluable in macros, mappings, and scripts where a substitution might not always apply, and an unexpected error would abort execution or leave an annoying message.
How it works
Normally, :s/pattern/replacement/ raises an error if the pattern isn't found, which can interrupt a macro mid-run. Adding e at the end of the flags list changes this behavior:
:s/old/new/e " no error if 'old' not found
:%s/TODO/DONE/ge " global substitution, silent on no-match
The e flag can be combined with other flags like g (global), i (case-insensitive), or c (confirm).
Example
Consider a macro that normalizes trailing spaces on lines that might or might not have them:
qa
:s/\s\+$//e
j
@aq
Without e, the macro would halt with an error on lines that have no trailing whitespace. With e, it silently skips them and continues.
Tips
- Use
:s/pattern//ento count the number of matches without substituting and without error: thenflag reports the count, andeprevents an error if there are zero matches - Essential when using
:argdo %s/old/new/ge | updateto refactor across many files where not all files contain the pattern - Also works with
:global::g/pattern/s/old/new/e