vi
Command - The Powerful Text Editor
Summary
The vi
command is a powerful, terminal-based text editor that has been a staple of Unix and Linux systems for decades. It's known for its efficiency and versatility, allowing users to create, modify, and navigate text files directly from the command line. While it has a learning curve, mastering vi
(or its improved version, vim
) can significantly boost your text editing productivity.
Introduction
vi
(Visual Editor) is a screen-oriented text editor originally created for Unix. vim
(Vi IMproved) is an enhanced version of vi
and is now the most commonly used version. Unlike GUI-based editors, vi
operates within the terminal window. It works in different modes - most importantly, command mode and insert mode. Command mode allows you to execute commands to navigate, delete, copy, paste, and save the file. Insert mode allows you to type and insert text into the file.
Use case and Examples
Opening a file with vi
Opens the filemyfile.txt
in vi
. If the file doesn't exist, it will be created. Creating a new file with vi
Creates a new file namednewfile.txt
. It opens in command mode, where you can enter commands to insert text. Inserting text
Pressingi
while in command mode switches to insert mode, allowing you to type text into the file. Saving and exiting
While in command mode, typing:wq
saves the changes to the file and exits vi
. Saving without exiting
While in command mode, typing:w
saves the changes to the file without exiting. Navigating with vi
In command mode, useh
(left), j
(down), k
(up), and l
(right) to move the cursor. Arrow keys also often work, but h, j, k, l
are more traditional and faster once you get used to them. Commonly used flags
Flag | Description | Example |
---|---|---|
+n | Open the file and position the cursor on line n . | vi +5 myfile.txt (Opens myfile.txt and puts the cursor on line 5.) |
-R | Open the file in read-only mode. | vi -R myfile.txt (Prevents accidental modification of the file.) |
+ | Open the file and position the cursor at the last line. | vi + myfile.txt |
-c command | Executes the specified vi command upon opening. | vi -c "/search_term" myfile.txt (Opens myfile.txt and searches for the search_term .) |