6

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.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
AJ.
  • 27,586
  • 18
  • 84
  • 94

2 Answers2

13

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_.

Community
  • 1
  • 1
pb2q
  • 58,613
  • 19
  • 146
  • 147
3

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
Dean
  • 8,632
  • 6
  • 45
  • 61