Vim tip 26: executing shell commands
You can execute external commands from within Vim. Here are some examples:
- :!ls execute the given shell command and display output
- the results are displayed as part of an expanded Command-line area, doesn't change contents of the file
- :.!date replace the current line with the output of the given command
- pressing !! in Normal mode will also result in :.!
!
waits for motion similar tod
andy
commands, !G will give :.,$!
- :%!sort sort all the lines
- recall that
%
is a shortcut for the range1,$
- note that this executes an external command, not the built-in
:sort
command
- recall that
- :3,8!sort sort only lines
3
to8
- :r!date insert output of the given command below the current line
- :r report.log insert contents of the given file below the current line
- Note that
!
is not used here since there is no shell command
- Note that
- :.!grep '^Help ' % replace the current line with all the lines starting with
Help
in the current file%
here refers to current file contents
- :sh open a shell session within Vim
- use
exit
command to quit the session
- use
See :h :!, :h :sh and :h :r for more details.
Video demo:
See also my Vim Reference Guide and curated list of resources for Vim.