2

move a code block from the file you are editing to another file using vim.

is there any tricks to be more productive?

This question is close to the url below, but not exactly the same

How can I extract a predetermined range of lines from a text file on Unix?

# tasks
identity lines range in file_A where you are working
append the code block to file_B
remove the code block from file_A

my previous routine - 4 steps

# write down line range, exit vim
sed -n 1,33p file.pl >> lib/module.pm
vim lib/module.pm - to check
vim file.pl again to delete the code block
Community
  • 1
  • 1
Gang
  • 2,658
  • 3
  • 17
  • 38

4 Answers4

10

If the destination file doesn't have to be opened, you can do it like this:

  • Select the lines with Shift-V + moving commands,
  • Execute the following command:

    :w >>file_B
    

    With an active selection it will actually display and execute:

    :'<,'>w >>file_B
    
  • Then just type gvd (or d']) to remove the previously selected text.

  • To avoid an error when the file does not still exist, add a bang ! to the write command:

    :'<,'>w! >>file_B
    
yolenoyer
  • 8,797
  • 2
  • 27
  • 61
2

Try the following:

  • Navigate to the first line you want to copy
  • Enter Visual Mode:

    Shift+v

  • Navigate to the last line you want to cut (lines between the first and last line are being visibly marked)
  • Delete the selected lines and save them to a buffer

    d

  • Open a new tab with the file you want the code to append:

    :tabnew /my/new/file

  • Navigate to the end:

    :$

  • Paste the previously deleted block:

    p

  • Save both files:

    :wa

Navigate between tabs with :tabnext and :tabprevious and close single tabs with :q.

Instead of using :wa, you can also use :wqa to write everything and quit immediately.

andreas-hofmann
  • 2,378
  • 11
  • 15
  • you are great, this is exactly what I am looking for, this has been bothered me for a long time.thanks – Gang Dec 26 '15 at 21:19
1

I would have make:


Open both file (shell):

$ vim -O2 file1 file2

delete and yank block

:l1,l2d  

where l1 and l2 are the line range you want to delete


switch window

<C-w>l

in normal


Paste bloc at the end of file

Gp
Gaut
  • 1,255
  • 2
  • 15
  • 33
1

As another solution, you could select the text (shift v), move the text to the clipboard register ("+x) , then switch to the new file and paste it ("+p)

This has the added advantage of working across vim-instances (if you ever do that for whatever reason).

DavisDude
  • 902
  • 12
  • 22