UNIX/Linux “vi” is a very powerful text editor, unfortunately at the beginning the utilization can be difficult. To help our memory, I wrote this post.
This is NOT an exhaustive guide, but a concentrate of the most useful commands and options.
vi Operation Modes:
Command mode: allows to execute administrative tasks (run command, move cursor, serch/replace string, save, etc.). This is the default mode when started.
When Insert mode is active press ESC to revert to Command mode.
Insert mode: enables to write into the file. To switch to Insert mode you simply type i.
To open a file in edit mode:
# vi filename
Basic Moving commands
Enable Command mode (pressing ESC twice) j -- Cursor down one line k -- Cursor up one line h -- Cursor left one line l -- Cursor right one line Multiple lines/columns move ex.: 5h -- Cursor 5 move left $ -- Cursor at the end of the line. 0 -- Cursor at the beginning of the line. Same than | b -- Cursor at the next word. w -- Cursor at the next word. G -- Cursor at the end of the file. 1G -- Cursor at the beginning of the line. :,4 -- Cursor at the 4th line.
Basic Editing commands
Enable Insert mode (pressing i) a -- Insert text after the cursor location. A -- Insert text at the end of the line. i -- Insert text before the cursor location. I -- Insert text at the beginning of the line. o -- Insert a new line below the cursor location. O -- Insert a new line above the cursor location. dd -- Delete the current line. x -- Delete the character under the cursor location. cw -- Change the word under the cursor location. r -- Replace the character under the cursor location. R -- Replace multiple characters starting from the cursor location. ESC to stop the replacement. yy -- Copy the current line. yw -- Copy the current word. p -- Paste the copied text before the current cursor location P -- Paste the copied text after the current cursor location
Basic Search and Replace options
Enable Command mode (pressing ESC twice) :set ic -- Ingnore case when searching. :set nu -- Disply line number on the left side. :%s/<search_string>/<replacement_string>/g -- Global search and replace
Exiting from vi
:q -- Exit without Saving :q! -- Force Exit without Saving :w -- Save the file :wq -- Save & Exit