Finding and replacing Vim

Often I want to search and replace in vim as follows:

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

Is there a way to make this syntax more efficient so that I can refer to <search_pattern> with a replace value? I think it will be something like a backlink to the group name / number, but I can not find any documents on this.

+6
source share
2 answers

Use the & symbol to represent a matching pattern in the replacement:

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

Alternatively, you can use \0 , which is a backlink for the entire matched pattern, and therefore it may be easier to remember:

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

See :help sub-replace-special

And thanks to @kev , you can forcefully remove the empty template at the end of the search string with \zs , which will be replaced with __foo_ in the replacement

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

This means: replace the end of the search string with __foo _.

+13
source

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

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

This will accomplish what you are looking for. If you need something more complicated using groups. To create a group, combine part of the search pattern with a (shielded) bracket. You can then reference this with \n , where n is the group number. An example will better explain this.

You have the following file:

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

Do you want to change any instance of bread,butter to bread and butter :

 :%s/\(bread\),\(butter\)/\1 and \2/g 
+3
source

Source: https://habr.com/ru/post/923053/


All Articles