Vim using variable contents inside search and replace expression

In vimscript, I defined a variable like this:

let b:myvar = 'abc'

Now, how can I insert the contents of this var into the search and replace, for example:

:s/123/&myvar/
+5
source share
2 answers

try this line:

:s/123/\=b:myvar/  
+3
source

Kent's answer works well for a spare part; for universal insertion when entering a wildcard command interactively, you can insert any expression (not just variables, but also functions, etc.) through <C-R><C-R>=(they should be printed as Ctrl+ R, and not literally):

:substitute/<C-R><C-R>=b:myvar<CR>/replacement/<CR>

Inside the script use :execute:

:execute 'substitute/' . b:myvar . '/replacement/'
+9
source

All Articles