Vim Recipes ‣ Editing ‣ Executing External Commands
You want to run a program from within Vim, possibly having it operate on the current file.
For example, you want to view a list of the other files in your project by getting a listing of the current directory. Or you want to find mistakes in the essay you're working on by passing its filename to the diction utility.
Invoke the program using the :!program syntax. For example, to view a directory listing on a POSIX system: :!ls.
If you need to pass the current filename to the command as an argument, use the % wildcard. For example, executing :!wc % from aristotle-essay.txt executes wc aristotle-essay.txt.
Filename Modifiers
You can alter the filename represented by % by following the wildcard with a modifier. For example:
- %:p
- Makes the filename a full path.
- %:.
- Makes the filename relative to the current directory.
- %:t
- Removes any directories before the actual file name. For example ~/work/foo.txt ⇒ foo.txt.
- %:e
- Removes everything except the filename extension. For example ~/work/foo.txt ⇒ txt.
The concept is that Vim suspends itself, asks your system to execute the command, shows you its output, then, once the user presses <Enter>, returns you to Vim.
If you don't want to see the output of the command, you can execute it like this: :silent command. (To also hide any error output: :silent! command).
You can use :redir > file if you want to save the output of a command to a file. You first execute, say, :redir > /tmp/output, then :!command. The output for command will be saved in the file /tmp/output, and displayed on the screen. (You can combine :silent command and :redir file to redirect a command's output to a file without seeing it on screen). To stop output redirection execute :redir END.
You can use :r!command to execute command and read in its output to the current file. For example, if you're using a POSIX system, you can insert your kernel version with :r!uname -v.