微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在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坚持在输出中写入整行,而我发现无法编写部分行.有什么想法吗?

我有两种(非常相似的)方法.使用内置的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

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

如果你想支持多个行范围,你可以扩展它以包含不同的条件,或者你可以将我的答案中的代码捏到this question.摆脱关于替换反斜杠的一点,然后你可以有一个非常简单的函数做像(未经测试的……)这样的东西:

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

原文地址:https://www.jb51.cc/vim/384933.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐