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.
[email protected]:~$ 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.
[email protected]:~$ 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 :
[email protected]:~$ 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.
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. 🙂