Working with the vi Editor
1. Introduction
vi (Visual Editor) is one of the most powerful and commonly used text editors in Linux/UNIX systems. It is a screen-based editor that allows users to create, edit, and manage text files efficiently using the keyboard.
๐ vi is available on almost every Linux system, especially servers.
2. Why vi Editor is Important
- Available by default on all Linux systems
- Very fast and lightweight
- Works in CLI (no GUI required)
- Preferred by system administrators
- Essential for server configuration files
3. Modes of vi Editor
vi works in three main modes (very important for exams):
1. Command Mode (Normal Mode)
- Default mode when vi starts
- Used for navigation, deletion, copying, saving
- Commands do not appear on screen
๐ Press Esc to return to command mode anytime.
2. Insert Mode
- Used to insert or edit text
- Text appears on screen
Commands to enter Insert Mode:
iโ insert before cursoraโ insert after cursoroโ open new line belowOโ open new line above
๐ Press Esc to exit insert mode.
3. Last Line Mode (Ex Mode)
- Used for saving, quitting, searching
- Commands start with
:
๐ Appears at the bottom of the screen.
4. Starting vi Editor
vi filename
Example:
vi file.txt
5. Basic Navigation Commands (Command Mode)
| Command | Action |
|---|---|
h | Move left |
l | Move right |
j | Move down |
k | Move up |
gg | Go to first line |
G | Go to last line |
0 | Start of line |
$ | End of line |
6. Editing Commands
Insert Mode Commands
| Command | Function |
|---|---|
i | Insert before cursor |
a | Insert after cursor |
o | New line below |
O | New line above |
Delete Commands (Command Mode)
| Command | Action |
|---|---|
x | Delete character |
dd | Delete line |
dw | Delete word |
d$ | Delete till end |
Copy & Paste
| Command | Action |
|---|---|
yy | Copy line |
p | Paste below |
P | Paste above |
7. Saving and Quitting (Last Line Mode)
| Command | Action |
|---|---|
:w | Save |
:q | Quit |
:wq | Save & quit |
:q! | Quit without saving |
:w filename | Save as new file |
8. Search and Replace
Search
/text
- Press
nfor next occurrence - Press
Nfor previous occurrence
Replace
:%s/old/new/g
- Replaces all occurrences
9. Undo and Redo
| Command | Action |
|---|---|
u | Undo |
Ctrl + r | Redo |
10. File Information Commands
:set number # show line numbers
:set nonumber # hide line numbers
11. Example: Editing a Configuration File
sudo vi /etc/hosts
Steps:
- Press
iโ insert text - Make changes
- Press
Esc - Type
:wq - Press Enter
12. Advantages of vi Editor
- Extremely fast
- Keyboard-based efficiency
- Minimal system resources
- Ideal for servers
- Powerful editing features
13. Disadvantages
- Steep learning curve
- Not beginner-friendly initially
14. Conclusion
The vi editor is a powerful, efficient, and essential tool in Linux. Understanding its modes and commands is crucial for system administration, server management, and exam preparation.
