Skip to content

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

vi myfile.txt
Opens the file myfile.txt in vi. If the file doesn't exist, it will be created.

Creating a new file with vi

vi newfile.txt
Creates a new file named newfile.txt. It opens in command mode, where you can enter commands to insert text.

Inserting text

i
Pressing i while in command mode switches to insert mode, allowing you to type text into the file.

Saving and exiting

:wq
While in command mode, typing :wq saves the changes to the file and exits vi.

Exiting without saving

:q!
While in command mode, typing :q! exits vi without saving any changes.

Saving without exiting

:w
While in command mode, typing :w saves the changes to the file without exiting.

Navigating with vi

h, j, k, l
In command mode, use h (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.)


Share on Share on

Comments