110

I would like to send contents of the current buffer to stdin of external command (like mail).

How do I send a Vim buffer to an external command?

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
yasar
  • 13,158
  • 28
  • 95
  • 160
  • Related questions for providing selected text as `STDIN` to shell commands: [Pipe to shell and receive output on info line](http://stackoverflow.com/questions/2575545/vim-pipe-selected-text-to-shell-cmd-and-receive-output-on-vim-info-command-line) and [Replacing the selected original text with the output](http://stackoverflow.com/questions/6932382/replace-vim-selection-with-output-of-shell-command) – user1129682 Feb 17 '14 at 18:05

2 Answers2

158

You can use :w !cmd to write the current buffer to the stdin of an external command. From :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 :!.

A related command is :%!cmd which does the same thing and then replaces the current buffer with the output of the command. So :%!sort would invoke the external sort command to sort the current buffer in place. From :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.
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

Here is example how to send the current buffer to external stdin from the command line:

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

It's useful for scripting purposes.

For more command-line tricks, check:

Community
  • 1
  • 1
kenorb
  • 155,785
  • 88
  • 678
  • 743