How to run Unix commands from within Vim?

84

27

How can I run Unix commands while I'm inside vim?

funk-shun

Posted 2011-05-18T23:05:51.113

Reputation: 1 503

Answers

111

Go to command mode Esc, then run :!unix_command. Anything run from the : prompt starting with a bang ! will be run as a unix shell command. You'll be shown the output and allowed to hit a key to get back to your work in vim.

If you have text selected in visual mode and want to send it TO a command as STDIN, hit !! and enter your command. The results of the command will replace the text you have selected.

Caleb

Posted 2011-05-18T23:05:51.113

Reputation: 4 323

2Something else that I think is worth noting is that this depends on the OS you're using. If you're using Windows, it'll execute a Windows shell command. Many people reading this will already know that, but for people coming from Google, I thought it would be worth mentioning. – Andrew – 2016-10-21T13:11:31.657

19Also, !! without any text selected will let you run a command and then insert the result at your current cursor position -- no need to send stuff to STDIN and replace it if you don't need/want to. – Kromey – 2011-05-18T23:36:34.847

8also, if you simply want to put the output of a command in your document, simply do :r!unix_command. This is usefull for commands such as date – Yab – 2011-05-19T06:01:23.140

3You can also execute multiple lines of your vi buffer by the shell (or any interpreter) and have them replaced by the result of the execution. eg: :10,20!sh or, form marked lines, 'a,'b!sh – jlliagre – 2011-05-19T11:58:53.697

25

From a VIM help mirror:

:shell        :sh[ell]        start a shell
:!            :!{command}     execute {command} with a shell

Jay Elston

Posted 2011-05-18T23:05:51.113

Reputation: 983

4

In addition to the above answers, you can use the current vim buffer content as stdin for shell command using :%!.

For example, suppose you want to filter lines from the current vim window content to contain only those with substring ca inside them. You could use:

:%! grep ca

Which will automatically filter the lines, placing the grep output instead of the current lines.

Omer Dagan

Posted 2011-05-18T23:05:51.113

Reputation: 161