Copying a line from one file to other using vi editor

Hi Guys,

the command ":yy" copies the line but it can be pasted in the same file. How can it be done if I want to copy it in other file.

Example: copy/write line 20 to file named newfile

:20w newfile

I'm using vi on Solaris. From command mode, name a buffer by using the double quote followed by the buffer name (in this case the letter a). Then follow that with the yank command to yank into the buffer. It looks like this (name a buffer "a" and yank 20 lines into it):

<ESC>"a20yy

Then, go over to the other file without leaving vi. If you started vi with both filenames as args, just :n to go to the next one. Otherwise, :e <name> to edit the other file. Once there, name your buffer, then what you want to do with it. In this case, "put" the lines from the buffer (name the buffer, then "put" its contents):

<ESC>"ap

For longer ranges of lines that are not practical to count, go to the bottom of the range you want to copy and use the "mark" command to mark that line (in this case, call the mark "x"):

<ESC>mx

Then, go to the top of the range you want to copy, name a buffer, and yank lines into the buffer from the current position to the "mark":

<ESC>"ay'x

Go to the other file and paste the contents of the buffer as mentioned above.

Gary

P.S. Some other tips. You can also:

<ESC>:r <filename>

to read the contents of filename into the current file, or:

!!<cmd>

to add the output of the cmd to the file (note no colon).

1 Like