Delete and redirect lines in Vim to another file

I want to delete the last 10 lines and move them to another file.

What am I doing now:

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

Is there a more efficient way I can do this?

+4
source share
4 answers

You can use ex commands instead. eg.

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

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


Using the code below in .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>) 

<h / "> In normal mode, the most effective, in my opinion, steps that you mentioned ( GV9k:w file.name gvd ).

+4
source

You can delete one step by following these steps:

  • visually select rows
  • :!> newfile.txt

This will use an external command to write lines to the specified file name and delete them at the same time, because nothing was output from this command.

If you want to add to the file instead of overwriting it, use >> instead of > .

+4
source

The direct way to write a series of lines to delete and delete after that you need to run the command

 :$-9,$w path | '[,']d 

However, this is inconvenient for frequent use if the file name is not constant.

The following is the MoveToFile() function that implements a command with the same name. All this includes the following two steps: write a series of lines using the command :write (see :help :w_f :help :w! , :help :w_a ), then delete this range. 1

 command! -nargs=* -complete=file -range=% -bang -bar MoveToFile \ :<line1>,<line2>call MoveToFile(<q-args>, <bang>0) function! MoveToFile(fname, overwrite) range let r = a:firstline . ',' . a:lastline exe r 'w' . ' !'[a:overwrite] . fnameescape(a:fname) exe r 'd' endfunction 

You can now use the command above to cover all commonly used use cases. For example, to move a visually selected range of lines to a file, use mapping

 :vnoremap <leader>m :MoveToFile 

This mapping produces a semi-complete command that calls :MoveToFile for the range of lines selected in visual mode ( '<,'> ). You only need to enter the file name and press Enter .

If you often do this for the last ten lines of the buffer, create a similar mapping for this case only:

 :nnoremap <leader>m :$-9,$MoveToFile 

1 The specified lines are deleted by default by overwriting its previous contents. Deleting strings without registers changes the last command in MoveToFile() to

 exe r 'd_' 

In this case :delete uses the black hole case (see :help :d and :help "_ ) instead of the standard one.

+1
source

As long as you use the visual mode to select lines, you can only delete recorded lines by pressing only three keys: d'> (see :help '> ).

+1
source

All Articles