Omit 'Pattern not found' error message in Vim script

Solution 1:

You can either use :silent or :silent! as a prefix to any command or you can add the 'e' option to the substitute, which is often easier.

:%s/x/y/ge
:silent! %s/x/y/g
:silent %s/x/y/g

For more information, see

:help :silent
:help :s_flags

The information on the e flag is a few paragraphs down from the :s_flags help.

Solution 2:

You might use silent:

:silent %s/x/y/g

or, if you need to do string manipulation to determine the strings to search and replace:

exec ":silent %s/x/" . varName . "/g"

I'm not 100% sure, but I think that silent only works in scripts.

Solution 3:

Probably a little bit off topic but i found this thread when searching for solutions for "search pattern not found" errors in vim, when i wanted to search for the next occurence in vim. The following map omits the error when pressing 'n'

map n :silent! /