'vim using contents of a variable inside search and replace expression
In vimscript I've defined a variable like this:
let b:myvar = 'abc'
Now how can I insert the contents of that var into a search & replace, eg:
:s/123/&myvar/
Solution 1:[1]
try this line:
:s/123/\=b:myvar/
Solution 2:[2]
Kent's answer works well for the replacement part; for generic insertion when typing the substitute command interactively, you can insert any expression (not just variables, also functions etc.) via <C-R><C-R>= (these must be typed as Ctrl + R, Ctrl + R, =, not literally):
:substitute/<C-R><C-R>=b:myvar<CR>/replacement/<CR>
Inside a script, you'd use :execute:
:execute 'substitute/' . b:myvar . '/replacement/'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kent |
| Solution 2 |
