Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute with contents of register or lines range from elsewhere in file in Vim

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> 
like image 784
Paolo Tedesco Avatar asked Mar 19 '09 15:03

Paolo Tedesco


People also ask

How to replace lines in Vim?

Basic Find and Replace 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.

How to replace word with another word in Vim?

Search for text using / or for a word using * . In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.

How to replace a word in Vim editor in linux?

Open the file in Vim. Press slash (/) key along with the search term like “/ search_term” and press Enter. It will highlight the selected word. Then hit the keystroke cgn to replace the highlighted word and enter the replace_term.


2 Answers

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

like image 79
David Wolever Avatar answered Sep 30 '22 21:09

David Wolever


:%s/foo/\=getline(10, 15)/g  :%s/foo/\=join(getline(10, 15))/g 
like image 36
Mykola Golubyev Avatar answered Sep 30 '22 20:09

Mykola Golubyev