vi

2024-11-04

Before exploring advanced editing, understanding basic navigation is crucial. vi operates in different modes:

Basic Navigation in Normal Mode:

Example:

Let’s say you have a file named mytext.txt with the following content:

This is a sample text file.
It contains multiple lines.
For demonstration purposes.

Open vi mytext.txt. Navigate to the end of the second line using 2G followed by $.

Editing and Deleting Text

Once you’ve navigated, you can edit and delete:

Example:

To delete the word “sample” from mytext.txt, navigate to the beginning of the word “sample” using 1G followed by w and then press dw. To insert “example” in its place, press i type “example” and press Esc to return to normal mode.

Searching and Replacing Text

vi offers powerful search and replace functionalities:

Example:

To replace all instances of “lines” with “sentences” in mytext.txt, use the command :%s/lines/sentences/g in command-line mode (press : first).

Working with Multiple Files

vi allows you to work with multiple files simultaneously. You can open multiple files using vi file1 file2 file3. The command :n switches to the next file, and :N switches to the previous file.

Example: Open two files file1.txt and file2.txt using vi file1.txt file2.txt and switch between them using :n and :N.

This introduction scratches the surface of vi’s capabilities. Exploring further commands and features will exponentially improve your text processing efficiency in Linux. Remember to consult the vi manual (man vi) for more detailed information.