Copy and paste content from one file to another file in vi

后端 未结 18 1406
南方客
南方客 2020-12-04 05:02

I am working with two files, and I need to copy a few lines from one file and paste into another file. I know how to copy (yy) and paste (p) in the same file. But that doesn

相关标签:
18条回答
  • 2020-12-04 05:02

    Use the variations of d like dd to cut.

    To write a range of lines to another file you can use:

    :<n>,<m> w filename
    

    Where <n> and <m> are numbers (or symbols) that designate a range of lines.

    For using the desktop clipboard, take a look at the +g commands.

    0 讨论(0)
  • 2020-12-04 05:03

    These remaps work like a charm for me:

    vmap <C-c> "*y     " Yank current selection into system clipboard
    nmap <C-c> "*Y     " Yank current line into system clipboard (if nothing is selected)
    nmap <C-v> "*p     " Paste from system clipboard
    

    So, when I'm at visual mode, I select the lines I want and press Ctrl + c and then Ctrl + v to insert the text in the receiver file. You could use "*y as well, but I think this is hard to remember sometimes.

    This is also useful to copy text from Vim to clipboard.

    Source: Copy and paste between sessions using a temporary file

    0 讨论(0)
  • 2020-12-04 05:06

    Goal: save a piece of one file to another file.

    Solution:

    1. Select the text you want to save:
      • Position the cursor where you want to start selection
      • Press v to select characters OR uppercase V to select whole lines
      • Move the cursor to the end of what you want to select
    2. Save selected text to the new file. Type :wSpace and the name of the new file. Actually you'll see

      :'<,'>w new.txt

      Then press Enter

    0 讨论(0)
  • 2020-12-04 05:12

    While editing the file, make marks where you want the start and end to be using

    ma - sets the a mark

    mb - sets the b mark

    Then, to copy that into another file, just use the w command:

    :'a,'bw /name/of/output/file.txt
    
    0 讨论(0)
  • 2020-12-04 05:12

    Another way could be to open the two files in two split buffers and use the following "snippet" after visual selection of the lines of interest.

    :vnoremap <F4> :y<CR><C-W>Wr<Esc>p
    
    0 讨论(0)
  • 2020-12-04 05:14

    These are all great suggestions, but if you know location of text in another file use sed with ease. :r! sed -n '1,10 p' < input_file.txt This will insert 10 lines in an already open file at the current position of the cursor.

    0 讨论(0)
提交回复
热议问题