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.
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.
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.
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.
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_.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With