Magazine

Editing Files with the Vi Editor

Posted on the 21 May 2021 by Satish Kumar @satish_kumar86

The vi editor is the most popular editor used to edit orcreatenew 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.

Thevim (short forvi improved) version of the vieditorcomes 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 ofoperationof 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,vieditor starts in Command Mode
  • Keystrokes in Command Mode are interpreted as commands to modify content
  • In this mode, you can givecommandsto 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 theI 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 LineModefrom 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 theEsckey is pressed

A

Insert the text at the end of the line, until theEsckey is pressed

i

Insert the text before the current cursor location, until theEsckey is pressed

I

Insert the text at the beginning of the line, until theEsckey is pressed

o

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

O

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

s

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

S

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

r

Replace the character at the current cursor position

R

Begin replacing text at the current cursor position until theEsckey 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

:x

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 filenamedemo

:w! demo2

Overwrites the file with the filenamedemo2

:f demo3

Renames the current file to the filenamedemo3

:w >> demo4

Appends the current file to the filenamedemo4

:5,10w demo5

Writes lines 5 through 10 to the filenamedemo5

:5,10w >>demo6

Appends lines 5 through 10 to the filenamedemo6

:r demo7

Reads the contents of the file with the filenamedemo7at the current cursor position

:e demo8

Opens another file with the filenamedemo8

: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 thelinenumber 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 (pressEnterto return to vi editor)

:!wc %

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

:sh

Temporarily returns to the shell prompt (typeExitto 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

hor Backspace

For move the cursor one character left

lor 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

 

0or^

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

 

:0or1Gorgg

For moving to the beginning of a file

:$orG

For moving to the last line of a file

:nornG

For moving to the nth line

Next, we will see howweto 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 yankycommand. 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^ord0

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

NddordNd

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^ory0

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

NyyoryNy

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


You Might Also Like :

Back to Featured Articles on Logo Paperblog

These articles might interest you :