I saw an editor command which started like this:

:%! sort

What does that mean? Specifically, the :%!.


2 Answers 2

:%! command

pipes the current file's contents to command's stdin, and replaces the file's contents with command's stdout.

So, :%! sort is pretty much the same as (from a shell) cat file | sort > tmp && mv tmp file.


From :help :%:

%       equal to 1,$ (the entire file)        *:%*

From :help :range!:

:{range}![!]{filter} [!][arg]               *:range!*
            Filter {range} lines through the external program

That is, %! sort and 1,$! sort are equivalent and they pass the text in the current buffer, from line 1 to the last line (that's what $ stands for), through the external sort command. After that, those lines are replaced by the command output. This is another explanation by @Carpetsmoker

That's useful not only for sorting a file. See some other examples here:

  • I still don't understand what this means for the above example I've given, how does it interact with the command line?
    – minseong
    Commented Oct 31, 2016 at 17:02
  • 1
    @theonlygusti, you might want to also look at :help filter. An excerpt: "A filter is a program that accepts text at standard input, changes it in some way, and sends it to standard output. You can use the commands below to send some text through a filter, so that it is replaced by the filter output. Examples of filters are "sort", which sorts lines alphabetically...."
    – Wildcard
    Commented Oct 31, 2016 at 22:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.