Skip to main content

VI editor

I consulted my team regarding the inclusion of vi editor in this blog. (this sounds cooler than I wasted 2 days dillydallying about this topic).

I will just give enough introduction to the most popular text editor in Linux editor, enough for you to create/open a file, make changes and save the file.

 To start vi editor, you give vi and filename.

Modes 

The editor has two modes insert mode and command mode. Insert mode is for you to type the content and command mode is for manipulation.

i - key starts insert mode
esc - key exits the insert mode

You can use even the following keys for starting insert mode
a - append at the end of word
o - start a new line below the cursor
O - start a new line above the cursor.


While typing remember the fact that, cursor keys are not allowed in insert mode.

Quitting the editor

First come out of the insert mode by typing esc key and use any of the following combinations - which appear at the bottom of screen


:w - save the file, but not quit
:wq - save the file and quit the editor
:q! - quit the editor without saving the file
:w filename - save as filename and do not quit

Deleting text

 Deleting the text in insert mode is difficult. So what I do is go back to command mode using esc key and try the following key combinations
  • dd - delete the current line
  • dw - delete the word starting from cursor
  • 2dd - delete two lines from current line (use any n instead of 2)
In all these delete commands, the deleted text is cut and placed in the buffer. This can be pasted using p command.

Copy (yank) and paste

When we delete text, it is placed in the buffer. So dd commands work like cut. The text cut can be pasted at cursor position using p command.

But if you want to copy and paste like ctrl c and ctrl v in other editors, you should use yank command -yy.
  • yy - yank the current line and put it in buffer
  • 2yy (nyy) - yank 2 lines from cursor (n lines) and put them in buffer
  • p - paste the buffer at cursor location
Now we have all the arsenal we need. We know how to quit, how to copy and paste.

Another useful command is undo

Undo command

:u command undoes the previous command. Next :u undoes the command before that and so on.

Save as command (:w)

:w and :wq save the current file. But what if we need to use an option similar to "save as".

For that we should use

 :w filename

File will be saved as the given name. :w n1.txt will save the content of editor as n1.txt and you can continue to edit n1.txt.

Read from file

To copy the content of another file into the current file, we must use :r command.

:r filename

The contents of this file will be inserted at the cursor position.

Comments