48

This is what I am attempting to do:

%s/Article/<h2>Article</h2>/gi

Unfortunately, every time i execute this command through my vim editor, it says:

Trailing characters

To mitigate the above, I executed the following:

%s/\s*\r*$//

And it executes successfully, but when I go back to the original search and replace command, it again reads 'Trailing characters' and does not execute the search and replace operation.

What am I doing wrong here?

Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
Parijat Kalia
  • 4,929
  • 10
  • 50
  • 77

2 Answers2

57

The "trailing characters" are in your command, not your document.

Vim thinks that you finished the command at Article</, then considers h2>/gi as the third argument of the substitute command. But those characters aren't all valid for the third argument, so it gives you the error.

To solve this, you need to escape the / character in your substitute.

%s/Article/<h2>Article<\/h2>/gi
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
  • 12
    You can use separators other than slash in `:substitute` command, so you don't have to escape `/` in the pattern (for example, `%s#Article#

    Article

    #gi`).
    – ib. Jul 16 '11 at 04:40
35

Also, if you often need to use literal forward slashes in your regexs (XML/HTML/UNIX file paths) and don't want to worry about escaping every instance, you can use a different delimiter. For example, using ! instead of /:

%s!Article!<h2>Article</h2>!gi

I am lazy and this is usually easier than manually escaping slashes.

Charlie Sanders
  • 421
  • 3
  • 2