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?
A straightforward way of writing a range of lines to file and deleting them afterwards is to run the command
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.1Now 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
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:
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()
toIn 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 '>
).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
In normal mode the steps you mentioned (
GV9k:w file.name gvd
) are the most efficient in my opinion.You can remove one step by doing this:
:!> 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>
.