VI-EDITOR Deep Dive

·

3 min read

VI-EDITOR Deep Dive

VI editor is a powerful and widely used text editor in UNIX and Linux operating systems. It allows us to create, edit and manage text files. Vim is the advanced version of the VI editor

There are three modes in VI :

  • Command mode

  • Escape mode

  • Insert mode


Basic commands in Command mode

vi <file-name>--> To open the file for editing

esc --> To go to command mode

esc + i --> To go to insert mode

esc + :w --> To save the file and continue editing

esc + :wq --> To save and quit from the file

esc + q! --> To quit from the file without saving

  • When we make any changes to the file, it wants us to save it, so if we want to forcefull quit we use "!"

esc + wq! --> To save and quit forcefully

w --> Write

q --> Quit

! --> Forcefully

  • yy — Yank (copy) a line of text.

  • p — Paste a line of yanked text below the current line.


Set and Unset the numbers

Initially go to insert mode & type some content

After typing content, press Escape & type the command

esc + :set nu --> To set the numbers for reference

esc + :set nonu --> TO remove the reference numbers


Find and Replace Strings

To find and replace a word in all lines of the file [Case Insensitive]

esc + :%s/<old_word>/<new_word>/ig

% --> All lines

s --> Substitute

i --> Case Insensitive Replace

g --> Globally i.e All the occurrences of the word in the lines will be replaced

$ --> Till the last line

To find and replace only on the 2nd line

esc + 2s/<old_word>/<new_word>/g

To find and replace from lines 2 to 4

esc + 2,4s/<old_word>/<new_word>/g

To find and replace from line 3 to the end of the file

esc + 3,$s/<old_word>/<new_word>/g

Search for a word in the file

esc + /<word>

'n' to goto the next word

'N' to goto the previous occurrence of the word

esc + /\c<word>

c --> Case-insensitive search


Delete a line

esc + dd --> To delete a line

esc + 2dd --> TO delete 2 lines

esc + :2,4d --> TO delete lines from 2 to 4

esc + :2,$d --> To delete lines from line 2 to the end of the file


Undo & Redo

esc + :undo --> To undo the changes

esc + :redo --> TO redo the changes