Edit a File in Linux Using vi
Overview
The vi text editor is a powerful tool for editing files directly from the command line. This guide will teach you the basics of vi, step by step, with practical examples and troubleshooting tips to ensure a smooth experience.
Opening a File in vi
To edit a file with vi
, open a terminal and type:
$vi filename
Replace filename
with the name of the file you want to edit. If the file doesn't exist, vi
will create it for you.
For example, to edit a configuration file, you might type:
$vi /etc/hosts
Enter Insert Mode to Start Typing
When you try to type, nothing happens. This is because you’re in Command Mode, which is
used to navigate and execute commands. Let’s switch to Insert Mode
, where you can type:
- Press i to enter Insert Mode
- Start typing your text
If you make a mistake, press the Esc
key to return to Command Mode, where you can delete or move around.
Tip: You'll see --INSERT-- at the bottom of the screen to confirm you're in Insert Mode.
Navigating Within the File
Navigation in vi
is done in Command mode. If you find you can't move the cursor, press the Esc key to ensure you're in Command Mode. Here are some basic movements:
- Arrow keys: Move up, down, left, and right
- h, j, k, l: left, down, up, and right
- G: Jump to the end of the file
- gg: Jump to the beginning of the file
- w: Move forward one word at a time
- b: Move backward one word at a time
Notice it doesn't say --INSERT-- at the bottom left corner, as we're in Command Mode.
Editing the File
Here's how to make changes to your file:
Insert Text
- Press
i
to enter Insert Mode - Type your text
- Press
Esc
to return to Command Mode
Delete Text
- x: Deletes a single character
- dd: Deletes an entire line
After using the dd command:
Undo Changes
Press u to undo your last action After using the u command:
Save and Exit
When you're done editing, use the following commands in Command Mode:
- :w: Save the file
- :q: Exit
vi
- :wq: Save and exit
To save your changes and exit:
- Press Esc to ensure you're in Command Mode
- Type :wq and press Enter
After typing :wq, you should be back to your terminal: