Writing to External Commands

I like to use Vim as a general place to manipulate text. Sometimes that means I paste text into an unsaved buffer, pipe it through a Unix command, and then further manipulate the buffer in Vim before finally yanking it and pasting it to another program.

One tool that makes this process easier is :w !cmd, where cmd, is a Unix command. For example, :w !wc will pipe the current buffer to the standard input of wc, giving me a neat character, word, and line count.

This works with unsaved buffers, which is perfect for quickly editing pasted text from a document or web page.

If you wanted to replace the contents of the current buffer you can use :%. This is a range that expands to 1,$ -- the entire file. You could use this with the indent command to format an entire file: :%!indent, or perhaps :%!gofmt for a Go program.

The way I remember how :w !cmd and :%!cmd works is to imagine that they write the current buffer to an external command. Once you get used to the idea you can send visual selections of text to and from different programs, which can be useful when you've got handy text processing tools like indent, gofmt, HTML tidy, and JSON formatters like json_pp.

blog comments powered by Disqus