在vim中,如何将部分行写入文件?

Mag*_*nus 9 vim

我想用vim将我文件的一部分写入另一个文件.例如,我有以下文件:

This is line 1

and this is the next line

我想要我的输出文件:

line 1

and this is

我知道如何使用vi将一系列行写入文件:

:20,22 w partial.txt

另一种方法是直观地选择所需的文本然后写:

:'<'> w partial.txt

但是,当使用这种方法时,vim坚持在输出中写入整行,并且我发现无法写出部分行.有什么想法吗?

DrA*_*rAl 8

我有两个(非常相似)的方法.使用内置的write命令无法做到这一点,但是生成你自己的功能相当容易,你应该做你想做的事情(你可以随意调用它 - 如果你愿意的话甚至是W).

一个只处理单行范围的非常简单的方法是使用这样的函数:

command! -nargs=1 -complete=file -range WriteLinePart <line1>,<line2>call WriteLinePart(<f-args>)

function! WriteLinePart(filename) range
    " Get the start and end of the ranges
    let RangeStart = getpos("'<")
    let RangeEnd = getpos("'>")

    " Result is [bufnum, lnum, col, off]

    " Check both the start and end are on the same line
    if RangeStart[1] == RangeEnd[1]
        " Get the whole line
        let WholeLine = getline(RangeStart[1])

        " Extract the relevant part and put it in a list
        let PartLine = [WholeLine[RangeStart[2]-1:RangeEnd[2]-1]]

        " Write to the requested file
        call writefile(PartLine, a:filename)
    endif
endfunction
Run Code Online (Sandbox Code Playgroud)

这称为:'<,'>WriteLinePart test.txt.

如果你想支持多个行范围,你可以扩展它以包含不同的条件,或者你可以从我对这个问题的答案中捏出代码.摆脱关于替换反斜杠的一点,然后你可以有一个非常简单的函数,它做了类似的事情(虽然未经测试......):

command! -nargs=1 -complete=file -range WriteLinePart <line1>,<line2>call writelines([GetVisualRange()], a:filename)
Run Code Online (Sandbox Code Playgroud)