Cut and paste text in vi or vim

Contributor Icon Contributed by qmchenry Date Icon March 21, 2004  
Tag Icon Tagged: UNIX

Cutting and pasting text in an editor is a basic requirement. This recipe describes the cut and paste functions of vi and vim.


Cutting text in vi/vim is achieved with the various delete commands which are summarized below:

dd Delete current line
D Delete from cursor to end of line
d$ Delete from cursor to end of line
d0 Delete from cursor to beginning of line
dw Delete from cursor to end of current word
db Delete from cursor to beginning of current word

These commands must be given in command mode in vi/vim, not insert mode. All of these commands can be preceded by a number that is interpreted as the number of operations to perform. For example, 5dd is interpreted as delete 5 lines.

When a deletion occurs, the text deleted is stored temporarily in a buffer. This buffer can be pasted into the document relative to the current cursor position using the p (lowercase p) paste after the current cursor position or P (upper case P) paste before the current cursor position commands.

Beware that some commands in vi/vim will empty the buffer. Cursor movement is safe, but since there is only one buffer that is used for both cut/copy/paste/undo/redo, any function that uses the buffer (insert, replace, etc.) will send your cut text to limbo.

Previous recipe | Next recipe |
 
  • steven hildenburg
    Does this work for external text?
    Say, i want to copy from my pc notpad file into an SSH window that is running VIM - do i select my text in notepad, press CTRL+V , then put my cursor in VIM and press p (in command mode).

    I only ever use linux from a distance to manage my website's config files - so i always feel quite lost.
  • steven hildenburg
    oops typo...i meant ..."press CTRL+C" - in notepad
  • Mikael Gunnarsson
    No, the text you copy in windows isn't automagically put into VI's buffer.

    To copy text from windows to the remote host you need to go into insert mode in VI and then use your SSH client's paste function.
  • Anonymous
    For example (with PuTTY), you would press Control+C on the text you want to copy, then switch to PuTTY, press i to insert text, then right click to have PuTTY paste the text in.
blog comments powered by Disqus