70

I'm using Vim, and I want to substitute some placeholder text with a long string, that spans several lines, which is already written somewhere else in the file.

Is it possible to replace a pattern with the contents of a register? Something like

:%s/foo/<contents of register A>

Otherwise, is it possible to replace with a range of lines? something like

:%s/foo/<content of lines from 10 to 15>
Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193

2 Answers2

95

According to http://vim.wikia.com/wiki/Search_and_replace It appears:

:%s/foo/\=@a/g

Also, pressing <c-r>a while in insert mode will insert the contents of register a.

Cool -- I never knew that. Good question.

Some other things to do with <c-r>: http://vimdoc.sourceforge.net/htmldoc/cmdline.html#c_CTRL-R

mrfred
  • 613
  • 4
  • 15
David Wolever
  • 148,955
  • 89
  • 346
  • 502
  • I'm impressed, you answered in less than one minute... Thanks! – Paolo Tedesco Mar 19 '09 at 15:52
  • I have always wanted to put things into commands that came from the system clipboard nice work. – ojblass Mar 23 '09 at 22:09
  • the vimdoc link is broken, use this one: http://vimdoc.sourceforge.net/htmldoc/undo.html#CTRL-R – 0x89 Dec 21 '09 at 22:08
  • 1
    Sadly it doesn't seem to work with other replacements like `%s/foo/xxx\=@axxx/g` – Wernight May 17 '12 at 08:05
  • @Wernight ah, yes – I suspect because that parses to "insert from register `axxx`". I don't know off the top of my head how to correctly escape that, but you might be able to get away with typing `%s/foo/xxx` then hitting `a`. – David Wolever May 17 '12 at 17:28
  • 1
    Nice. Note that the same syntax doesn't work for using a register in the search pattern, however: http://stackoverflow.com/questions/3922384 – Nathan Long Aug 03 '12 at 13:49
  • 6
    @Wernight I wanted to do something similar and seeing as how I've kind of learned my way around vim doc now I was able to find what I'm looking for. `\=` starts a sub-replace-expression. When the substitute string starts with with `\=` it treats the rest of the string as an expression. So instead of doing `%s/foo/xxx\=@xxx/g` you would do the following `%s/foo/\="xxx" . @a . "xxx"\g`. – PaddyDwyer Jun 01 '14 at 13:52
  • @Wernight Could you please post this as an answer so it can be bookmarked? – raratiru Aug 22 '14 at 21:04
25
:%s/foo/\=getline(10, 15)/g

:%s/foo/\=join(getline(10, 15))/g
Mykola Golubyev
  • 57,943
  • 15
  • 89
  • 102
  • I think that's the opposite of what he's looking for... I think he wants something like :s/foo/10,15/ – David Wolever Mar 19 '09 at 15:55
  • Maybe I didn't express myself clearly, but what I wanted to achieve was replacing 'foo' with **the contents** of lines from 10 to 15, and not limit the replacement to lines 10-15. Thanks for answering, anyway :) – Paolo Tedesco Mar 19 '09 at 15:56
  • Works perfectly, I'm just sorry I cannot accept more than one answer. Thanks! – Paolo Tedesco Mar 19 '09 at 16:01