Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete and redirect lines in Vim to another file

Tags:

vim

vi

scripting

I want to delete say last 10 lines and move it to another file.

What I currently do is:

  • select last 10 lines in visual mode,
  • write these lines by :'<,'>w to other file,
  • and then delete selected lines.

Is there any more efficient way I can do this?

like image 956
shampa Avatar asked Oct 11 '11 01:10

shampa


2 Answers

You can remove one step by doing this:

  • visually select the lines
  • :!> newfile.txt

This will use an external command to write the lines to the given filename, and simultaneously delete them because nothing was output from the command.

If you want to append to a file instead of overwriting it, then use >> instead of >.

like image 155
Jamie Avatar answered Sep 27 '22 20:09

Jamie


You can use ex commands instead. e.g.

:1,10w file.name   Write the first ten lines

:$-9,$w file.name Write the last ten lines (the dollar sign denotes last line)


With the code below in your .vimrc you can use the command :MoveTo file.name
function! MoveLastLines(f)
  exe '$-9,$w ' . a:f    "write last ten lines to the passed filename
  $-9,$d                 "delete last ten lines
endfunction

command! -nargs=1 -range MoveTo :call MoveLastLines(<f-args>)


In normal mode the steps you mentioned (GV9k:w file.name gvd) are the most efficient in my opinion.
like image 26
Eric Fortis Avatar answered Sep 27 '22 21:09

Eric Fortis