Append or prepend selected text to a file in Vim

What about

  1. v
  2. some movement command/even search to select the text
  3. :'<,'> w! >> /YOUR/SELECTIONFILE
  4. :'<,'>d

Is that what you want? If so set up a map for it, like

map <F2> :'<,'> w! >> /YOUR/SELECTIONFILE<cr>:'<,'>d<cr>

Note this appends to SELECTIONFILE, and not only the selection, but the whole lines. Also, read :h :w and :h ++opt (in which you can learn about the possible options for writing files (e.g.) you can append to a file with different encoding, which really messes things, so don't do that ;-)


You can write text selected by vim marks into a file using the below commands.

For example you go to line :20 and then mark it ma and then go to line 30 :30 and mark it mb and then copy lines 20 to 30 to file filename.dat :'a,'b w filename.dat.

:'a,'b w filename.dat to write lines from mark a to mark b into file filename.dat

:'a,'b w! filename.dat to replace the existing file filename.dat with lines from mark a to mark b

:'a,'b w >> filename.dat to append lines from mark a to mark b into file filename.dat


You can do it in three steps:

  • type Shift-vj...j to select some lines
  • type :'<,'>w! >>file.bak to save selected lines to file.bak(append)
  • type gvd to delete original lines

You can write a user-defined command Sbak if you like:

com! -nargs=1 -range Sbak call MoveSelectedLinesToFile(<f-args>)
fun! MoveSelectedLinesToFile(filename)
    exec "'<,'>w! >>" . a:filename
    norm gvd
endfunc