Lesson 20: Editing text files with vi(m)¶
Many Linux users decide to use vi or vim (Vi IMproved) as a text editor over Nano because of its efficiency to insert, delete, find and replace text only using the keyboard. This tutorial will just explain the basic usage of Vim however, there are many additional features to perform advanced tasks and to personalise the Vim editor which are not covered here. Additional reading material can be found online.
We can open the 'earth.txt' file by typing:
[learner planets]$ vim earth.txt
Vim offers many operational modes however, we are going to focus on the core operational modes: command and insert. By default, Vim opens in command mode.
Command mode¶
The mode to issue internal commands to Vim, browse, navigate and delete text; nothing is displayed in the bottom left corner. There are many commands available to Vim but some of the most used commands are listed below. Additional commands are listed in an online cheat sheet, available here.
Command Behaviour
---------------------------------- ----------------------------------------------------------------------------------------------------------------------------
Insert/i/I/a/A/o/O Enter insert mode
/ Search for string in current file. Navigate between matches with `n` key for forward searches or `N` for backward searches
:wq Write file to disk and quit the editor
:q and :q! Quit without saving with a warning, or no warning, respectively
:<line_no> i.e. :20 Move the cursor to the first character on <line_no>
dd Delete the entire row the cursor is currently on
u Undo last change
Ctrl+R Redo last change
:%s/original/replaced/g Replace string 'original' with 'replaced' globally
Insert mode¶
The mode to add, edit, replace and delete text; the bottom left corner
displays -- INSERT -- to signify insert mode. Any key (excluding
command keys i.e Esc, PrtScn, Num Lock, etc.) pressed will print literal
text to the current file. Press Esc
to return to command mode.
Insert mode can be entered by pressing the Insert
key if operating in
any normal mode. Pressing the Insert
key again will toggle to
--REPLACE -- mode which will overwrite text when typing.