Search code examples
vimsavebackupselection

Append or prepend selected text to a file in Vim


In Vim, is there a way to move the selected text into <current_file>.bak, appending or prepending? If possible, the backup file should not be displayed.

I envision the workflow to be:

  1. Select some text
  2. Type :sbak
  3. The selection is saved into <current_file>.bak

Solution

  • 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