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 todandycommands, !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
:sortcommand
- recall that
- :3,8!sort sort only lines
3to8 - :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
Helpin the current file%here refers to current file contents
- :sh open a shell session within Vim
- use
exitcommand 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.