How do I pipe the entire buffer through an external shell command like sort, jq, or a formatter?
Answer
:%!command
Explanation
:%!{command} replaces the entire buffer contents with the output of piping them through a shell command. This makes Vim a direct interface to Unix text-processing tools — sort, format, transform — without leaving the editor.
How it works
%is a range meaning "all lines in the buffer"!signals that what follows is a shell command- The buffer's content is sent to the command's stdin, and stdout replaces the buffer
You can also filter a visual selection or a line range instead of the whole file:
:'<,'>!sort " sort only the selected lines
:5,10!column -t " align columns on lines 5-10
Example
Format a messy JSON buffer:
:%!python3 -m json.tool
Before:
{"name":"alice","age":30,"city":"NYC"}
After:
{
"name": "alice",
"age": 30,
"city": "NYC"
}
Tips
:%!sort -usorts and removes duplicates in one step:.!datereplaces the current line with the output ofdate:%!cat -nadds line numbers to the buffer- If the command fails or produces no output, Vim warns you and you can undo with
u - In normal mode,
!{motion}{cmd}also filters the range covered by the motion