A common sequence of events when editing files is to make a change and then need to test by executing the file you edited in a shell. If you're using vim, you could suspend your session (ctrl-Z), and then run the command in your shell.
That's a lot of keystrokes, though.
So, instead, you could use vim's built-in "run a shell command"!
:!{cmd} Run a shell command, shows you the output and prompts you before returning to your current buffer.
Even sweeter, is to use the vim special character for current filename: %
Here's ':! %' is in action!
A few more helpful shortcuts related to executing things in the shell:
-
:!By itself, runs the last external command (from your shell history) -
:!!Repeats the last command -
:silent !{cmd}Eliminates the need to hit enter after the command is done -
:r !{cmd}Puts the output of $cmd into the current buffer

6 comments:
you can also use "%!" to pass current buffer via some filtering command.
For example : %!nl - to number lines (different from :set nu), :%!wc to check word count on current buffer, :%!tac to reverse order of lines, and so on.
Yes, and you can also send line ranges rather than the whole buffer, for example, lines 4-7:
:4,7! sort -u
or line 4 through end of file:
:4,$! sort -u
And when a visual selection is active, that will automatically be the range used:
:! sort -u
And in a homologous fashion, one can read the results of an external command by passing the command to run to the :r command like so:
:r !/bin/ls
Chris, that's the final example Selena gave in the original post, isn't it?
Yes, indeed. I must have missed that part somehow. Apologies for the noise.
@depesz & Jon: Yes! Sorting is one of @gorthx's (Gabrielle Roth) favorite uses :)
Thanks for sharing!
Post a Comment