在Vim中将缓冲区传输到外部命令

113

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

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


与将选定文本作为“STDIN”提供给shell命令相关的问题:在信息行上管道到shell并接收输出用输出替换所选原始文本 - user1129682
2个回答

162

你可以使用 :w !cmd 将当前缓冲区写入外部命令的标准输入(stdin)。参考文档 :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.

6
这很有用,可以将json格式化为::'<,'>!python -mjson.tool:%!python -mjson.tool - TrinitronX
2
对于格式化 Go 代码,请使用 :%!gofmt 命令,去掉最后一个 %,因为这会导致其使用已保存的版本(可能与当前缓冲区不同)。 - thomasrutter
有没有办法在成功时仅使用命令输出替换当前缓冲区?如果命令返回非零值,则不要替换缓冲区。 - thomasrutter
@thomasrutter 如果缓冲区被替换为错误消息而不是预期的输出,您只需按u撤消即可。 - törzsmókus
我已经四处寻找“:%!我的命令”的文档,但是几乎没有发现。这个在哪里可以找到相关文档呢? - Russia Must Remove Putin
@AaronHall 我已经在我的答案中添加了帮助描述。我不怪你,我也花了很长时间才找到它。 - John Kugelman

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接