Move section to new file in vim

I have a section in file1 that should be moved to file2 . I usually did this by visually selecting a block, deleting it :wq from file1 , open file2 , then paste.

Is there an easy way to move a block of text from file to file2 without closing vim ?

+8
vim
source share
4 answers

You can open your new file in a split with :sp newfile , and then remove the block as usual from your first file. Then move on to another split using ctrl w and w . Then use p to put the deleted content in another file.

+5
source share

As an alternative:

  • write the selection to a new file :'<,'>w file2

  • then reselect and delete with gvd

The first step is described in vimtutor Lesson 5.3: SELECTING TEXT TO WRITE .

+20
source share

You can open the file in a new buffer.

just open the file with :e file2 and paste the text. To quickly move between buffers, use either :e # or :b #

see :help buffers for more information

+2
source share

Since no one mentioned this: you can use tabs instead.

  • Select your block.

  • Delete it with d

  • Create a new buffer in a new tab with :tabnew newfile.name

  • Insert it and save with p and :w

  • You can return with gT or close the current tab with :q

Personally, new usage buffers are only tabs. Read more about them in :help tabpage

+2
source share

All Articles