Editing files with the vi editor

May 21, 2021

The vi editor is the most popular editor used to edit or create new files from a shell prompt. It comes in text-based as well graphical interface form, with extended features. This text-based editor is used to write a script, edit system configuration files, or develop the source code of a programming language. The name vi is pronounced as vee-eye.

The vim (short for vi improved) version of the vi editor comes with many enhancements to make working with the vi editor easier. It supports extended features, such as syntax highlighting for many configuration files and programming languages. Whatever we learn about vi editor is applicable to vim also, so we will learn about the vi editor in this section.

There are three modes of operation of the vi editor, as follows:

  • Command Mode
  • Insert Mode
  • Line Mode

The following diagram shows the different modes of vi editor, along with the keys used to switch between them:

vi editor

When working with the vi editor, it is essential to keep track of the mode you are working in. Many commands and keystrokes behave differently in different modes. The following table describes the different modes and their features in brief:

Mode

Feature

Command Mode

  • By default, vi editor starts in Command Mode
  • Keystrokes in Command Mode are interpreted as commands to modify content
  • In this mode, you can give commandsto perform cut, delete, copy, and paste operations, and also use keystrokes to navigate in the file
  • Editing and the insertion of text are not possible in this mode

Insert Mode

  • Press the I key to switch to InsertModefrom Command Mode (pressing theI key to get into Insert Mode is the most commonly used option; however, there are other keys too that can be pressed to get into Insert Mode from Command Mode)
  • Insert Mode is used to modify or insert text into a file
  • Insert Mode is indicated by- - INSERT - - at the bottom of the screen
  • Pressthe Esc key to exit Insert Mode and return to Command Mode

Line Mode

  • Press the : key to switch to Line Mode from Command Mode only (we cannot switch to Line Mode from Insert Mode directly)
  • Line Mode is indicated by the : colon key at the beginning of the last line of the vi editor and the cursor is placed immediately after this colon
  • We can use line editing commands inherited from older line editors, such as saving the contents of a file to disk, executing shell commands, and reading other files’ contents, and so on
  • Requires pressingthe Enter key after the command for execution
  • Press the Esc key to exit Line Mode and return to Command Mode

Working with files in vi editor

To start the vi editor and edit the file, use the following syntax:

$ vi <filename>

If the file exits with the specified filename, it will be opened and its contents are displayed in Command Mode. If the file does not exist, vi creates the file when it is saved on the disk for the first time. By default, vi uses an unnamed temporary buffer where the file is edited, until its contents are saved to disk. Now, let’s understand the workings of vi in different modes in detail.

Insert Mode

This mode is used to enter new text in a file or modify the existing text in the file. There are multiple ways to get into Insert Mode, as described in the following table:

Key

Usage

a

Insert the text after the current cursor location, until the Esc key is pressed

A

Insert the text at the end of the line, until the Esc key is pressed

i

Insert the text before the current cursor location, until the Esc key is pressed

I

Insert the text at the beginning of the line, until the Esc key is pressed

o

Insert a new line following the current cursor location for entering text, until the Esc key is pressed

O

Insert a new line preceding the current cursor location for entering text, until the Esc key is pressed

s

Delete the character at the current cursor location and remain in Insert Mode, until the Esc key is pressed

S

Delete the line with the current cursor location and get into Insert Mode, until the Esc key is pressed

r

Replace the character at the current cursor position

R

Begin replacing text at the current cursor position until the Esc key is pressed

Line Mode

This mode is used to execute editing commands. The most popular operations performed in this mode include saving a file to disk, closing a file, and exiting vi editor without saving a file to disk. Line Mode operations require the Enter key to be pressed after the command is typed. Some of the most popular operations performed in Line Mode are described in the following table:

Operations

USAGE

Save and exit operations

 

:q

Quits the vi editor only if no changes have been made to the file being edited

:q!

Quits the vi editor without saving the current changes in the opened file

:wq

Writes/saves the contents of the file to disk and exits the vi editor

😡

Writes/saves the contents of the file to disk and exits the vi editor

ZZ

Writes/saves the contents of the file to disk and exits the vi editor from Command Mode

Write/save to file operations

 

:w

Writes/saves the contents of the file to disk

:w demo

Writes/saves the contents of the file to the disk with the filename demo

:w! demo2

Overwrites the file with the filename demo2

:f demo3

Renames the current file to the filename demo3

:w >> demo4

Appends the current file to the filename demo4

:5,10w demo5

Writes lines 5 through 10 to the filename demo5

:5,10w >>demo6

Appends lines 5 through 10 to the filename demo6

:r demo7

Reads the contents of the file with the filename demo7 at the current cursor position

:e demo8

Opens another file with the filename demo8

:e#

Switches between opened vi windows (note: this works only if you have saved the file once on disk using :w)

Search file contents

 

/<pattern>

Searches the occurrence of specified patterns of text, inside buffers, in a forward direction.

?

Searches the occurrence of specified patterns of text, inside buffers, in a backward direction.

n

Repeats the last search command in a forward direction

N

Repeats the search command in the opposite direction

We can perform substitution in Line Mode. By default, it performs substitution on the current line only; however, we can prefix the substitution command s with the address option to perform substitution on multiple lines, as shown in the following table:

Line Mode command

Description

Substitution on current line

 

:s/file/book

Substitutes the first occurrence of file with book on the current line

:s/file/book/g

Substitute all occurrences of file with book on the current line

Substitution between address range (x,y) specified

 

:1,5s/cat/dog/

Substitutes the first occurrence of cat with dog between lines 1 and 5

:1,5s/cat/dog/g

Substitutes all occurrences of cat with dog between lines 1 and 5

Substitution in current file (%)

 

:%s/cat/dog/

Substitutes the first occurrence of cat with dog throughout the file

:%s/cat/dog/g

Substitutes all occurrences of cat with dog in whole file

:%s/cat/dog/gc

Prompts before each substitution and substitutes all occurrences of cat with dog throughout the file

Determining line numbers in Line Mode of vi editor

Line Mode has the ability to determine the line number of the current line, or the total number of lines in a file being edited.

The following table lists the commands that are used to determine line numbers:

Command

Description

:.=

This returns the line number of the current line at the last line of the screen

:=

This returns the total number of lines at the last line of the screen

Ctrl + g

This tells the current line number, along with the total number of lines in the file at the last line of the screen (Command Mode keystroke combination)

How to execute external commands in Line Mode

Being able to execute shell commands from within the vi editor is sometimes quite useful. The following table lists some examples of shell command execution from Line Mode:

Line Mode command

Description

:! <shell command>

Executes a shell command (press Enter to return to vi editor)

:!wc %

Executes the wc command on the file opened in vi editor (% represents the file currently being edited)

:sh

Temporarily returns to the shell prompt (type Exit to return to vi editor)

:r !<shell command>

Reads the output from a shell command into the opened file at the current cursor position

Command Mode

This is the default mode of vi editor. In this mode, most navigation and browsing of file content is performed. Besides the navigation of file content, we also perform cut, delete, copy, and paste operations in Command Mode. The following table describes the popular navigation operations of Command Mode:

KEY

USAGE

Move by character

 

Arrow keys

For moving the cursor up, down, left, and right

j or <enter>

For move the cursor one line down

k

For move the cursor one line up

h or Backspace

For move the cursor one character left

l or Space

For move the cursor one character right

Move by word

 

w

For moving the cursor to the beginning of the next word

b

For moving the cursor to the previous word

e

For moving the cursor to the end of the current word

Move by line

 

0 or ^

For moving the cursor to the beginning of the line

$

For moving the cursor to the end of the line

Move by sentence

 

(

For moving the cursor to the beginning of the previous sentence

)

For moving the cursor to the end of the next sentence

Move by paragraph

 

{

For moving the cursor to the beginning of the previous paragraph

}

For moving the cursor to the end of the next paragraph

Move by screen

 

Ctrl + F or Page Down

For moving forward one screen

Ctrl + B or Page Up

For moving backward one screen

Ctrl + D

For moving down half a screen

Ctrl + U

For moving up half a screen

H

First line on screen

M

Middle line on screen

L

Last line on screen

Move inside whole document

 

:0 or 1G or gg

For moving to the beginning of a file

:$ or G

For moving to the last line of a file

:n or nG

For moving to the nth line

Next, we will see how we to perform cut, delete, copy, and paste operations in Command Mode. The deletion of a character puts the text in an unnamed temporary buffer. The deleted character stored in a temporary buffer can be pasted at other places. Hence, we can say that a delete and paste operation is similar to a cut and paste operation.

The copying of character is known as yanking in context of vi editor. Copying (yanking) is performed using the yank y command. The following table describes various cut, copy, delete, and paste operations in vi editor:

KEY

USAGE

Deleting/cutting single characters

 

x

Deletes a character at the current cursor position

Nx

Deletes the N-1 character on the right-hand side, starting at the current cursor position

3x

Deletes a total of three characters, starting with the character currently under the cursor position, followed by the next two on the right-hand side

X

Deletes a character to the left of the cursor

Deleting/cutting larger chunks

 

dw

Deletes the word at the current position up to the next space or next punctuation

db

Deletes one word backward

d$

Deletes the line from the current cursor position to the end of the line

d^ or d0

Deletes the line from the current cursor position to the beginning of the line

dG

Deletes from the current line to the end of the file

dgg

Deletes from the current line to the beginning of the file

D

Deletes the rest of the current line

dd

Deletes the current line

Ndd or dNd

Deletes N lines from the current line

Copying/yanking text (puts text into a temporary buffer)

 

yw

Yanks (copies) a word forward

yb

Yanks (copies) a word backward

y$

Yanks (copies) the line from the current cursor position to the end of the line

y^ or y0

Yanks (copies) the line from the current cursor position to the beginning of the line

yy

Yanks (copies) the current line and puts it in a buffer

Nyy or yNy

Yanks (copies) N lines and puts them in a buffer

p

Pastes the contents below the current line (the yanked line or lines from the buffer)

P

Pastes the contents above the current line

u

Undoes the previous operation

Ctrl + R

Redoes the last undo operation

Related Articles

How to Install MongoDB on CentOS 8 Linux

How to Install MongoDB on CentOS 8 Linux

MongoDB is an open-source and free NoSQL document based database system. Nowadays, it is prevalent as most application developers are using MongoDB, which can handle big data. As a MongoDB is a NoSQL database, It stores data in JSON-like documents where fields can...

read more
How to Install OpenCV on CentOS 8 Linux

How to Install OpenCV on CentOS 8 Linux

OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in commercial...

read more

Lorem ipsum dolor sit amet consectetur

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

four × two =