Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append or prepend selected text to a file in Vim

Tags:

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
like image 622
greatghoul Avatar asked Feb 06 '12 13:02

greatghoul


People also ask

What is the difference between append and insert in Vim?

The append command will put the cursor after the current position, while the insert command will put the cursor before it. Using the append command is like moving the cursor one character to the right, and using the insert command.

How do I insert multiple lines at the beginning of vim?

vim Inserting text Insert text into multiple lines at once Press Ctrl + v to enter into visual block mode. Use ↑ / ↓ / j / k to select multiple lines. Press Shift + i and start typing what you want. After you press Esc , the text will be inserted into all the lines you selected.


2 Answers

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 
like image 94
kev Avatar answered Sep 18 '22 16:09

kev


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 ;-)

like image 25
Zsolt Botykai Avatar answered Sep 22 '22 16:09

Zsolt Botykai