This tip shows how to capture the output from running an external (or shell) command in Vim. Vim has many useful functions which can replace shell commands, such as strftime() or glob(), but sometimes only the shell command will do. See :help function-list for a list of Vim's built-in functions.
The results from running a shell command can be inserted into the current buffer with the
:read command, or lines can be replaced in a buffer with a filter command, or Vim's
system() function can be used like the backquote syntax (aka backtick) that many Unix shells provide to capture command output, which you can then use in a script or expression-register (:help quote=) to insert in the buffer or parse in some way.
The following examples capture the output of the shell's
date command. This is just an example: it is better to use Vim's
strftime() function to get the date or time.
:read command can insert a file or the result from running an external program into the current buffer. To run a program, preface the shell command with
! (see :help :read!). For example,
inserts the current date on a new line below the current line on most Unix-like systems (on Windows, use
:read !date /t).
If a line number is specified, the new text is inserted after that line. For example,
:12read !date inserts the result after line 12, and
:$read !date inserts the result after the last line. To insert the result before the first line, specify line 0 (
As a convenience, a user command (named
R) can be defined to allow easy capture of output in a scratch buffer:
:command! -nargs=* -complete=shellcmd R new | setlocal buftype=nofile bufhidden=hide noswapfile | r !<args>
On a Unix-based system, the command
:R ls -l would open a new window listing all files in the current directory, while on Windows commands such as
:R dir or
:R dir /b /a-d might be used.
The following example (for Unix) finds all files in or below the current directory that were modified in the last week (under 8 days); those files are searched for the text "vim", and all matching lines are listed in a new window:
:R find -mtime -8 | xargs grep vim
If you don't want the command output on a line by itself, or if you don't want it inserted, you can use the system() function. For example, to put the current date into a variable named
curdate, which you can then use inside a script, use:
system() is the most flexible method as it allows a script to process the result before any output. For example, the function below appends the output of the command (if successfully executed) to the end of the current line. The script demonstrates these important concepts:
- Use system() to capture the output of an external command in a script.
- Use shellescape() to escape any arguments to an external command to avoid passing possibly dangerous commands to the shell.
- Use setline() to change text without moving the cursor.
After sourcing the following script, press F8 to append the result from running the command to the current line. The
date -u command, which works on Unix-based systems, outputs UTC time.
nnoremap <F8> :call GetDate('')<CR> function! GetDate(format) let format = empty(a:format) ? '+%A %Y-%m-%d %H:%M UTC' : a:format let cmd = '/bin/date -u ' . shellescape(format) let result = substitute(system(cmd), '[\]\|[[:cntrl:]]', '', 'g') " Append space + result to current line without moving cursor. call setline(line('.'), getline('.') . ' ' . result) endfunction
strftime() as explained at date or time is a better option for capturing timestamps. For example, the following command provides a mapping to append a tab character and the local time to the current line when F5 is pressed:
nnoremap <F5> m'A<C-R>="\t".strftime('%Y-%m-%d %H:%M')<CR><Esc>``
In the mapping,
A (append) enters insert mode at the end of the current line. Ctrl-R followed by
= inserts the expression register, which evaluates the following expression, finishing with
CR (Enter). The expression is
"\t" (tab character), concatenated with the
strftime() result. The final
Esc exits from insert mode. The initial
m' sets the previous context mark, and the final
`` jumps to that location to restore the cursor position after the append.
Using a filter command
A filter is a program which reads text from standard input, then processes the text, and sends the result to standard output. In Vim, a range of lines can be selected, then replaced with the output from running a filter (the selected lines are the input to the filter).
For example, the following text may appear in a file that is being edited:
One,Two,Three,Four,Five arborist,apple,artichoke,ant,author branch,banana,broccoli,bee,book canopy,cherry,cabbage,cricket,codex
The following procedure uses the
cut utility (available on many Unix-based systems) to replace each line with fields 2 to 3 inclusive:
- On the first line, press V to start a visual selection.
- Press j to move the cursor down until all wanted lines are selected.
- Press ! (the command line will show :'<,'>! indicating that the selected range will be filtered).
- Enter a command to be executed by the shell, such as
cut -f2-3 -d,(select fields 2-3 using comma as a delimiter between fields).
Vim saves the selected lines to a temporary file, then runs the external command with the temporary file as input. The result from running the command replaces the selected lines. In this example, the result is:
Two,Three apple,artichoke banana,broccoli cherry,cabbage
Using a filter to replace a command with its output
You can use this feature to replace a command with its output. For example on Windows if the buffer contains
ping -n 1 188.8.131.52 ping -n 1 184.108.40.206 ping -n 1 220.127.116.11 ping -n 1 18.104.22.168 ping -n 1 22.214.171.124
and you issue the command
:%!cmd the five lines will be replaced with the output of the five commands.
The same method can be used on Unix with appropriate changes (for bash you would issue the command
%!bash, and in this example the ping command would be
ping -c 1).
Above it is mentioned that using
system() is like using backtick expansion in many shells. It should be noted that Vim actually does support real backticks in some situations. See :help backtick-expansion for details. This means you can do things like:
to open a new buffer with a name matching the current date. This even works on Windows! The :help does not make it clear, but this works using the cmd.exe shell:
:new `date /t`
This also provides a way to use Vim expressions where expressions are not normally allowed. For example, rather than using:
:exe 'e' filename_in_var
you can use:
- Display output of shell commands in new window
- script#4224 offers a way to execute a command cmd using ":echo system(cmd)", but tipping ":! cmd" (note the space). As a benefit you get completion for commands like for ":!", and you don't leave vim.
Comment from old tip which should be mentioned somewhere:
:echo system("dir ".expand("%"))
Following are relevant:
- 2 Easy edit of files in the same directory
- 193 Insert current filename
- 311 Open the folder containing the currently open file
- 432 Putting the current file on the Windows clipboard
- 530 Get the name of the current file
- 600 Copy filename to clipboard
- 891 Copy parts of filename to clipboard
- 1055 Faster directory browsing from command line
JohnBeckett 05:28, April 18, 2011 (UTC)