Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim Search and Replace Efficiency

Tags:

replace

vim

Often I want to search and replace in vim like this:

:%s/<search_pattern>/<search_pattern>_foo/g

Is there a way to make this syntax more efficient so that I can reference <search_pattern> in the replace value? I'm thinking it would be something similar to back referencing by group name/number, but I can't find any docs on this.

like image 464
AJ. Avatar asked Aug 16 '12 17:08

AJ.


People also ask

How do I find and replace a word in Vim?

The simplest way to perform a search and replace in Vim editor is using the slash and dot method. We can use the slash to search for a word, and then use the dot to replace it. This will highlight the first occurrence of the word “article”, and we can press the Enter key to jump to it.

How do you do a search and replace string in Vim?

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 we search for old and replace it with new in Vim?

It's simple to search and then decide if you want to keep or replace each result in a file: Execute a regular search with / . Use the keystroke cgn on the first result to replace it. Type n or N to go to the next result.


2 Answers

Use the & character to represent the matched pattern in the replacement:

:%s/<search_pattern>/&_foo/g

Alternately you can use \0, which is a back-reference for the whole matched pattern, and so may be easier to remember:

:%s/<search_pattern>/\0_foo/g

See :help sub-replace-special

And, thanks to @kev, you can force an empty pattern at the end of your search string using \zs, to be replaced by __foo_ in the replacement:

:%s/<search_pattern>\zs/_foo/g

This means: replace the end of the search string with __foo_.

like image 185
pb2q Avatar answered Nov 01 '22 09:11

pb2q


You can either use & for the entire search pattern, or you can use groups to match a section of the pattern. Using &:

:%s/<search_pattern>/&_foo/g

This would accomplish what you're looking for. If you need something a little more complex use groups. To make a group, surround part of the search pattern with (escaped) parenthesis. You can then reference that with \n, where n is the group number. An example would explain it better.

You have the following file:

bread,butter,bread,bread,bread,butter,butter,etc

You want to change any instance of bread,butter to bread and butter:

:%s/\(bread\),\(butter\)/\1 and \2/g
like image 42
Dean Avatar answered Nov 01 '22 09:11

Dean