Tuesday, April 13, 2010

Vim - Cut and Paste a Block of Text Between 2 Files

Vim is my editor of choice, but I would never consider myself an expert. So when I wanted to copy text from one text file to another in vim, I was challenged. Although I was frustrated for a brief moment, I remembered uncle google and he helped me with my conundrum. So here is how you cut and paste a section of text from one text file to another using vim.

First open your first text file in vim. Scroll down to the first line of the block of text you wish to copy and press "ma" (that is m followed by a, without the quotation marks). "m" marks the beginning of your block. The "a" makes the assignment of copying the text to buffer "a".

Now scroll to the end of the block of text you wish to copy and press "y'a" (again without the quotes). The "y" yanks the text block. The single quote in the middle, I guess designates the end of the block and "a" again identifies the buffer being used.

Next open the second text file by typing ":split filename.txt" (Remember no quotes). This will open the second text file in a split vim session window. Scroll to the line where you would like the text pasted and press "p" (You should know, don't include the quotes). This will paste the block of text on the line below the current cursor position. Save and your done.

Please leave comments with other examples of cutting and pasting in vim.
Enjoy.

6 comments:

Matthew said...

"v" or "V" puts you in Visual mode, where you can see what you are yanking, move around with your favorite movement keys, "y", and finally "p".

Niky45 said...

:args file1 file2
V,then you select what you want, y
:next , then you get to the point you want to paste, p

i learned to do it this way the other day. works fine

Ceno said...

I find it easier to open a new tab with :tabnew and copy paste like Matthew said, ctrl-pgup/down to move between tabs. Remember that you can always define keyboard shortcuts for this, so a CTRL-T is surely in order.

richs-lxh said...

Hey Jared, long time no see. I got into vim heavily in my job and have come to worship its power. I would just like to add that in your vim config file you can actually force vim to use the global clipboard so that you can paste any copied text.


set clipboard="unnamed"

richs-lxh said...

Hey Jared, long time no see (AX). I got into vim heavily in my job and have come to worship its power. I would just like to add that in your vim config file you can actually force vim to use the global clipboard so that you can paste any copied text.


set clipboard="unnamed"

Anonymous said...

Of course in Vim there's always another way :-)

Place the cursor where you want the text to go and use :read filename.txt to insert that text without ever leaving the current window or opening the other file.

This assumes you want most or all of filename.txt