How to Use Vim Editor in Linux: Basic Commands and Tips
To use the
vim editor in Linux, open a terminal and type vim filename to edit or create a file. Use i to enter insert mode for typing, Esc to return to command mode, and :wq to save and exit.Syntax
The basic syntax to open or create a file with Vim is:
vim filename: Opens the file namedfilenameor creates it if it doesn't exist.- Inside Vim, you switch between modes: command mode and insert mode.
- Use
ito enter insert mode to type text. - Press
Escto return to command mode to run commands. - To save and exit, type
:wqin command mode and pressEnter.
bash
vim filename
Example
This example shows how to create a file, add text, save, and exit Vim.
bash
vim example.txt # Inside Vim: # 1. Press i to enter insert mode. # 2. Type: Hello, Vim! # 3. Press <Esc> to return to command mode. # 4. Type :wq and press Enter to save and exit.
Output
File 'example.txt' is created with the text 'Hello, Vim!'
Common Pitfalls
Beginners often get stuck because Vim starts in command mode, so typing letters won't insert text until you press i to enter insert mode.
Another common mistake is trying to exit Vim with Ctrl+C or Ctrl+Z, which does not save changes.
Always press Esc to enter command mode, then use :wq to save and quit, or :q! to quit without saving.
bash
Wrong way: # Type text immediately after opening Vim (no insert mode) Right way: # Press i to enter insert mode before typing # Press Esc to go back to command mode # Use :wq to save and exit
Quick Reference
| Command | Description |
|---|---|
| vim filename | Open or create a file named filename |
| i | Enter insert mode to type text |
| Esc | Return to command mode |
| :w | Save changes without exiting |
| :wq | Save changes and exit Vim |
| :q! | Exit Vim without saving changes |
| u | Undo last change |
| /text | Search for 'text' in the file |
Key Takeaways
Open files with 'vim filename' and switch between insert and command modes.
Press 'i' to start typing and 'Esc' to stop typing and run commands.
Save and exit with ':wq' and quit without saving with ':q!'.
Remember Vim starts in command mode, so you must enter insert mode to type.
Use the quick reference commands to navigate and edit efficiently.