There are some eventualities wherever UNIX or linux admin desires to run UNIX commands and insert the output of commands in vi editor while not leaving it. this could be possible using below steps :

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

:!Command

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

root@clinerds:~$ sudo vi /etc/hosts

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.

root@clinerds:~$ sudo vi /etc/hosts

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 :

root@clinerds:~$ sudo vi /etc/hosts

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>

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

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