【问题标题】:Piping buffer to external command in Vim在 Vim 中将缓冲区管道传输到外部命令
【发布时间】:2011-12-13 14:52:03
【问题描述】:

我想将当前缓冲区的内容发送到外部命令(如邮件)的标准输入。

如何将 Vim 缓冲区发送到外部命令?

【问题讨论】:

标签: vim pipe external


【解决方案1】:

您可以使用:w !cmd 将当前缓冲区写入外部命令的标准输入。来自:help :w_c

                                                        :w_c :write_c
:[range]w[rite] [++opt] !{cmd}
                        Execute {cmd} with [range] lines as standard input
                        (note the space in front of the '!').  {cmd} is
                        executed like with ":!{cmd}", any '!' is replaced with
                        the previous command :!.

一个相关的命令是:%!cmd,它做同样的事情,然后用命令的输出替换当前缓冲区。所以:%!sort 将调用外部排序命令对当前缓冲区进行排序。来自:help :range!

:{range}![!]{filter} [!][arg]                           :range!
                        Filter {range} lines through the external program
                        {filter}.  Vim replaces the optional bangs with the
                        latest given command and appends the optional [arg].
                        Vim saves the output of the filter command in a
                        temporary file and then reads the file into the buffer
                        tempfile.  Vim uses the 'shellredir' option to
                        redirect the filter output to the temporary file.
                        However, if the 'shelltemp' option is off then pipes
                        are used when possible (on Unix).
                        When the 'R' flag is included in 'cpoptions' marks in
                        the filtered lines are deleted, unless the
                        :keepmarks command is used.  Example: 
                                :keepmarks '<,'>!sort
                        When the number of lines after filtering is less than
                        before, marks in the missing lines are deleted anyway.

【讨论】:

  • 这对于格式化 json 很有用::'&lt;,'&gt;!python -mjson.tool:%!python -mjson.tool
  • 对于格式化 go,使用 :%!gofmt 而不使用最后一个 %,因为这会导致它使用保存的版本(可能与当前缓冲区不同)
  • 有没有办法在成功时用命令输出 only 替换当前缓冲区?如果命令返回非零,不替换缓冲区?
  • @thomasrutter 如果缓冲区被替换为错误消息而不是预期的输出,您只需按u 即可撤消
  • 我在:%!my command 上查看过很多文档,但发现非常很少。这方面的文档在哪里?
【解决方案2】:

以下是如何从命令行将当前缓冲区发送到外部标准输入的示例:

vim -es +"w >> /dev/stdout" -cq! /etc/hosts

它对脚本很有用。

更多命令行技巧,请查看:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2013-10-13
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多