How to run Linux Commands within vi/vim editor

There are some scenarios where UNIX or Linux admin wants to run linux commands and insert the output of commands in vi editor without leaving it. This can be possible using below steps :

First Go to command mode in vi editor by pressing ‘esc‘ key and then type “:“, followed by “!” and the command, example is shown below.

:!Linux_Command

Example : Run the ifconfig command within the /etc/hosts file.

linuxtech[email protected]:~$ sudo vi /etc/hosts

ifconfig-command-in-editor

Insert Linux/Unix Command Output in vi editor :

To insert the output of a UNIX or Linux command into a file, immediately after the cursor use below syntax in vi editor

:r!command

Example: Insert the output of hostname in /etc/hosts file.

[email protected]:~$ sudo vi /etc/hosts

insert-unix-command-output

When we press enter , the output of hostname command will be inserted in the file just after the cursor position.

Starting a shell within vi Editor

We can start the UNIX shell within the editor , to start a shell use below command :

:<Shell>

Type of a shell that is started is determined by the $SHELL variable. And to return back to editor use exit or Ctrl-D

Example : Start sh shell in vi editor :

[email protected]:~$ sudo vi /etc/hosts

shell-in-vi-editor

Note: Above discussed features becomes very useful if you are using vi/vim to document a UNIX command and you wanted to include examples of the output from this command.

Open an existing file within the vi editor

Let’s assume we have already open /etc/hosts file using vi editor and want to open and edit /etc/resolv.conf without leaving the vi editor, this can be done by using below in command mode,

:e<file-to-be-edit>

edit-exiting-file-vi-editor

Once we hit enter it will open /etc/resolv.conf file, do the change whatever you want and then save and exit the file.

save-exit-file-vi-editor

That’s all from this article, i hope these tips will help you to work on vi and vim editor more efficiently.

1 Response

  1. Shawn H Corey says:

    You can filter lines through a shell command. For example, to sort some lines:

    Go the the top of the lines and press: ma

    Go to the bottom of the lines and press: !’asort
    and then RETURN.

    The lines will be sorted. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest