开发者

Delete and redirect lines in Vim to another file

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?


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 >.


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.


A straightforward way of writing a range of lines to file and deleting them afterwards is to run the command

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

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

Below is the function MoveToFile() implementing the command with the same name. The whole thing wraps the following two steps: write a range of lines using :write command (see :help :w_f, :help :w!, :help :w_a), then delete that 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

Now you can use the above command to cover all frequent use cases. For example, to move visually selected range of lines to file use the mapping

:vnoremap <leader>m :MoveToFile

This mapping triggers semi-complete command calling :MoveToFile for the range of lines selected in Visual mode ('<,'>). You need only to type a file name and hit Enter.

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

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

1 Specified lines are deleted into the default register overwriting its previous contents. To delete lines without affecting registers change the last command in MoveToFile() to

exe r 'd_'

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


While you use visual mode for selecting lines, you can delete just written down lines pressing only three keys: d'> (see :help '>).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜