Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace in VIM results in trailing characters

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?

like image 935
Parijat Kalia Avatar asked Jul 16 '11 00:07

Parijat Kalia


People also ask

How do I delete a trailing character in Vim?

Every time the user issues a :w command, Vim will automatically remove all trailing whitespace before saving.

How do I search and replace in Vim?

Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.

How do I find and replace every incident of a text string in Vim?

When you want to search for a string of text and replace it with another string of text, you can use the syntax :[range]s/search/replace/. The range is optional; if you just run :s/search/replace/, it will search only the current line and match only the first occurrence of a term.

How do you replace a word with another word in Vim?

Search for text using / or for a word using * . In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.


1 Answers

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 
like image 140
Merlyn Morgan-Graham Avatar answered Sep 21 '22 01:09

Merlyn Morgan-Graham