Mastering Vi/ViM Editor

Ankit Ojha
6 min readAug 30, 2023

--

While working with CLIs, we always encounter textual data. And, how fast and efficiently we can work with those textual data plays a significant role in getting things done and saving us time.

In this article, we are going to learn about the ViM editor and how we can use this tool for editing texts (files) on Linux machines.

What is Vi/ViM?

Vi (Visual) is the most powerful and iconic text editor tool available on Linux Systems and ViM (Vi IMproved) is just a newer and more advanced form of Vi.

Unlike nano editor, we do not get any keyboard shortcuts provided right in the text editor with Vi, so it may seem daunting at first. However, it is guaranteed that using Vi/ViM editor will increase our efficiency and productivity while working with texts.

Different modes of Vi Editor

There are 4 different modes in Vi Editor and each of these modes carries a specific purpose. So, one must have a clear understanding of all these different modes for an efficient text editing experience.

  1. Command Mode
  2. Insert Mode
  3. Escape/Ex Mode
  4. Visual Mode

Command Mode

This is the default mode with Vi and it is active as soon as we open a file with Vi editor.

In this mode, we can only edit (delete/paste/copy) texts in the file but, cannot perform write operations. It may look like, we can just start typing, but we may get some unexpected behavior when we try to do so.

Some of the operations that we can perform in this mode will be:

h : Move one character left
l : Move one character right

j : Move one line down (Alt: Enter)
k : Move one line up

O : Move to the beginning of the current line
$ : Move ot the end of the current line

gg : Move to the top of the file
G : Move to the bottom of the file

'N'G : Move to the N(th) line of the file

w : Move one word ahead
b : Move one word back

) : Move one sentence ahead
( : Move one sentence back

} : Move one paragraph ahead
{ : Move one paragraph back

b : Move to the beginning of the word
e : Move to the ending of the word

u : Undo previous change(s), if done in the file

yy : Copy the current line (yanking texts)
p : Paste the copied line

dd : Delete the current line
'N'dd : Delete 'N' number of lines below from the current line
dw : Deletes a word
Ndw : Deletes 'N' words
x : Delete a single character at the cursor

:set number : Show line number before each line in file (temporary)

Insert Mode

This is the mode that allows us to insert texts into the file.

This mode is activated upon simply typing ‘i’ in command mode. Whatever we now type, the Vi editor will insert the characters rather than interpreting them as commands.

Now, there are various ways we can switch to this mode, rather than just using ‘i’. It depends on our use case. Some of the ways are:

i : Insert text before the current cursor pointer
a : Insert text after the current cursor pointer

l : Insert text from beginning of the current line
A : Insert text from end of the current line

o : Open a new line below the current one
O : Open a new line above the current one

s : Substitute the current character
S : Substitute the current line

r : Replace the current character
R : Replace the current line

Escape Mode / Ex Mode

This mode helps us perform tasks like saving files and executing commands.

It is activated by typing ‘:’ or ‘/’ when the Vi is in command mode. The cursor will then move to the last line of the screen and the vi editor waits for commands given by the user to perform respective actions.

Various operations that can be performed in this mode are:

Searching Texts:
/text : Perform search in forward direction (Top-to-bottom)
?text : Perform search in reverse direction (Botton-to-Top)
n : Search next occurance of the searched text in forward direction
N : Search next occurance of the searched text in backward direction

Save and Exit:
:w : Save the changes
:wq : Save changes into the current file and exit (Alt command-> :x)
:wq! : Forcefully save into the read-only file
:q! : Exit without saving the changes

NOTE: To save and exit we can also use -> ZZ (capital Z) / Shift + zz (if caps lock is not ON)

Replacing Texts with matching patterns:
:s/<exitstingWord>/<newWord>/g : Replaces word(s) in the current line
:%s/<existingWord>/<newWord>/g : Replaces every word(s) in the file
:%s/<existingWord>/<newWord>/gc : Prompts before making substitutions, c is added at end

Move/Copy existing lines to another line inside the document:
:NcopyM : 'N' refers to the line to be copied and 'M' is the line number where it will be pasted
:NmoveM : same as above, except the line will be moved instead of copying

Some more Tips and Tricks with Vi/ViM:

Password protect a file:

To password-protect a file, type :X (capital X) in the command mode and we will be asked to enter the desired encryption key.

Now, save and exit the file using the command-> :wq

Also, we can simply remove the encryption key by again typing :X in command mode and when prompted with the encryption key, leave it blank to remove the password. And, finally :wq to save the changes and exit.

Recovering unsaved data of a file after a crash:

Let’s suppose that we are trying to make changes to a file named ‘newfile’ and due to some unforeseen circumstances (like server crash), our file could not be saved properly.

Now, in order to recover our unsaved data of that file, we just need to edit the file named .<fileName>.swp.

The ‘ls -al’ command will show the .swp file of your original file which was stored in the virtual memory (swap memory).

After editing the file, simply save it and we are good to go. Also, remove the old .filename.swp file after performing necessary operations.

Invoke external binaries or external files within vim:

Sometimes, we might need to insert the output of other commands directly in our file being edited.

Or, often me might encounter with situation where we need to append the contents of another file to the file that we are currently editing.

In such cases, we might use of this technique to get what we want.

:r! <binary> : To invoke external binaries inside the file
:r </path/to/external/file> : To copy the contents of external file to current file

Examples:
:r! netstat -tulpn | grep LISTEN
-> This will print the output of that command in the current file

:r /etc/passwd
-> This will copy the contents of /etc/passwd in the current file

Change letters, words or entire lines to UPPERCASE or lowercase:

This is performed in the Ex mode of the vim.

NOTE: X refers to the number (or an integer value)

For UPPERCASE
-------------
For letters:
Position the cursor to the first letter, then type gUX and press right arrow key.

For words:
Place the cursor at the beginning of the word, then type gUXw

For entire line:
Place the cursor anywhere in the line, then type gUU

NOTE:
For lowercase, everything is same, except we should use 'u' instead of 'U' in each command.

More about Vi/ViM:

To learn more about this tool, we can use following commands:

  1. man vim -> This will display the manual page for vim editor.
  2. vimtutor -> This is a built-in tutor for Vi/ViM editor in Linux systems.

Conclusion

In this article, we talked a lot about Vi/ViM editor and how we can use it efficiently to work with textual data.

However, there are still many more tips and tricks to cover. Please feel free to share them in comments section below.

Thank you for your time.

--

--

Ankit Ojha

DevOps Engineer | SRE | Cyber Security | Linux | Cloud Enthusiast