10

I am comparing a couple of files with vimdiff. There are some differences which I expect and which I'd like to get rid of. I know I can use:

:%s#from1#to1#g | %s#from2#to2#g | ...

to replace multiple expected differences at the same time. However, the 2nd substitution is only executed if the first succeeds; i.e. from1 must be present in the file in order to replace from2, too (I get E486: Pattern not found: from1 and from2 still exits). Can I specify multiple optional substitutions that all should be executed? I imagine some option for | to behave like an or instead of an and.

I would like to do this interactively because the expected differences differ among various files and I don't exactly know them in advance.

1 Answer 1

12

Add the e flag to your :s commands:

:%s#from1#to1#ge | %s#from2#to2#ge

From the flag's entry at :help :s_flags:

[e]     When the search pattern fails, do not issue an error message and, in
        particular, continue in maps as if no error occurred.  This is most
        useful to prevent the "No match" error from breaking a mapping.  Vim
        does not suppress the following error messages, however:
                Regular expressions can't be delimited by letters
                \ should be followed by /, ? or &
                No previous substitute regular expression
                Trailing characters
                Interrupted

A second option would be to use :silent! to suppress error messages:

:silent! %s#from1#to1#g | :silent! %s#from2#to2#g

This will suppress all output and errors though, so the e flag is probably better for :substitute commands, but using :silent! is useful if you want to suppress all errors and for other commands.

2
  • 1
    Thanks. The silent is helpful in my case: I replace inside read-only files (without saving) so I get also another warning.
    – Rolf
    Jan 2, 2017 at 9:59
  • @Rolf, the same here. Martin, thanks for the help!
    – JavaRunner
    May 3, 2021 at 3:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.