Home > Articles

This chapter is from the book

Working with vi

Course Objectives Covered

  1. Creating, Viewing, and Appending Files (3036)

  1. Introduction to Linux Text Editors (3036)

  2. Using Command Line Editors to Edit (3036)

  3. Using Desktop Editors to Edit Files in the Linux System (3036)

When vi came into being, it was a revolutionary application. This was in the early days of Unix, and the editors that came with the operating system were incredibly crude and difficult to manage. Many times, you could not see the line you were working on (as with ed); instead, you would specify the line, specify the change, and then ask to see the line printed to tell if your change was correct.

The vi editor (pronounced "v—eye") was created by a graduate student named Bill Joy (later to become famous as one of the founders of Sun Microsystems). He created an editor that was visual—hence the "v"—and interactive—hence the "i". With this editor, you can see the lines in the file, and see the changes being made as you make them.

By today's standards, vi is now considered to be crude—who wants to work with such an application when such entities as WordPerfect and Microsoft Word exist? The answer is that you must know the basics of this editor because it is a powerful administrators' tool. The following points are among its benefits:

  • Every version of Linux ships with this editor—you can be assured that it will reside on whatever machine you use.

  • It has very low overhead. When a system is damaged and configuration files must be modified before it can be brought up, you are often prevented from starting large applications. This minimal overhead is possible because vi does not have the buttons and scrollbars common in GUI (graphical user interface) applications.

  • Though considered a "screen" editor, vi also incorporates features from "line"-type and "command"-style editors.

The learning curve can be steep when first starting with vi. Lacking are the function keys and other niceties. In their place are mnemonics ("u", for example, stands for undo, and "o" for open a line, and so on).

Starting vi

You start vi by typing vi on the command line along with the name of a file to create (if it does not already exist) or edit (if it does already exist). If the file you want to work on is in a directory other than your present working directory, you can supply the full path to the file as well.

The following example starts vi in the current directory to create a file named first:

$ vi first

Because the file does not already exist, this brings up a blank screen with tildes (~) used to signify that you are working in the file that is currently empty. There is one tilde for each blank line on the screen. The information at the bottom of the screen gives the filename and the fact that it is a "New File."

If the file does exist, the lines of the file are shown (and any blanks within the screen are indicated by tildes). The bottom of the screen now reports the name of the file and the number of lines and characters.

Regardless of whether the file is new or existing, vi always starts automatically in command mode. This means it is waiting for you to tell it to do something. You cannot just start typing away or begin making changes—you must first tell it what to do.

Navigation

The easiest commands involve navigation. Table 3.5 lists the navigation keys that can be used in vi.

vi Navigation Keys

Key

Result

-

Move to the first character of the previous line

$

Move to the last position of the current line

(

Move backward one sentence

)

Move forward one sentence

{

Move to the beginning of the previous paragraph

}

Move to the beginning of the next paragraph

^

Move to the first character of the current line (ignoring spaces)

+

Move to the first character of the next line

0

Move to the beginning of the current line

b

Move backward to the beginning of the previous word

B

Move backward to the beginning of the previous word, ignoring symbols and punctuation

e

Move to the end of the next word

E

-Move to the end of the next word, ignoring symbols and punctuation

ENTER\

Move to the beginning of the next line RETURN

h

Move left one space

j

Move down one line

k

Move up one line

l

Move right one space

w

Move to the beginning of the next word

W

Move to the beginning of the next word, ignoring symbols and punctuation

G

Move to the last line of the file

xG

"Goto" line number x


The last entry of the table signifies that a line number can be used in conjunction with "G" to move to that line: For example, 5G will move the cursor from wherever it happens to be in the file to line 5. The ability to use numbers with commands is a constant throughout all of vi—if you precede a command by a number, it is interpreted as meaning you want to do something a number of times equal to that number. For example, the command 10h will move the cursor 10 spaces to the left.

The arrow keys can also be used for navigation, but only if they are mapped correctly on the terminal. In order for them to function properly, the right arrow must send the same key sequence as pressing l would, the left arrow must send the same key sequence as pressing h would, and so on.

Changing Text

When you reach a word to be changed, there are an almost endless number of ways to make the change. In the earlier table, the letter "w" was used to signify a word when discussing navigation. Using similar mnemonics, it can be combined with "c" for change and thus the command becomes cw.

This tells the editor that you intend to change the word, so it removes the current word from view, and places the editor in "insert" mode. You now enter a new word, and then press Esc to exit out of insert mode and enter command mode once again.

NOTE

Whenever you want to exit insert mode, regardless of the method used to place you into it, you always press Esc to return to command mode.

There are a number of combinations that the change command can be used in conjunction with. Table 3.6 offers a synopsis of the possibilities.

vi Change Text Combinations

Key Sequence

Result

c$

Change from here to the end of the line

c)

Change from here to the end of the sentence

c^

Change from here to the beginning of the line

c}

Change the remainder of the paragraph

3cw

Change the next three words

r

Replace an individual character

R

Go to "Replace" mode—overwriting exiting text with new text


Notice that so many of the choices in Table 3.6 begin with the current cursor position and making changes from that point to the beginning or end of the line. If you need to change an entire line, regardless of where the cursor resides within the line, you can use the command cc. In a similar vein, the command C is the same as c$; selecting all text from the current cursor position to the end of the line.

Saving Files

After a change has been made, and you are finished with the editor, it is time to save the file. Just like everything in vi, there are numerous ways to accomplish this. Most of the ways require entering command mode, and this is accomplished by pressing the colon key (:) and typing another command.

NOTE

As a matter of history, the use of the colon to precede a command is a carryover from an earlier editor: ex.

You can save the file, under its current name, by typing

:w

This saves (writes) the file, but leaves you in the editor. To exit the editor, you then enter

:q

You are then returned to the Linux command-line prompt, having quit the editor. This sequence is useful if you want to write your changes out several times prior to quitting, as you can always enter :w and continue with edits.

If you want to write and quit at the same time, however, you can combine the operation into a single command:

:wq

This will write the file and quit the editor. A shortcut to this operation (which makes no mnemonic sense whatsoever) is to enter ZZ, which will also write and quit.

If you want to save the file by a different name (for purposes such as keeping the original intact), you can use the :w syntax and follow it by the new name. It is worth pointing out at this point that if you make any changes to a file, the default operation of vi is to not let you exit the editor until you save the changes. If you try to leave by using :q, you will be notified that changes have been made with an error message:

No write since last change (use ! to override)

The error message spells out what must be done to get around the default. If you made changes that you do not want to save—having clobbered too much text to undo, changed your mind, and so on—you can exit the file and leave it in the state of the last save operation with this command:

:q!

Saving a Portion of a File

Not only can you save the entire file, but vi allows you to save only part of a file by specifying the line numbers you want to write. By now you've probably figured out that every line can be referenced by a number, and this operation requires using this syntax:

:first_line, last_linew FileName

Pay special attention to the "w" attached to the last line number. This must be there to identify the operation as a write request. Two wildcards can be used for either line number specification:

  • $ to signify the last line in the file

  • . to signify the current line

Some examples of commands to save only a portion of the file are shown in Table 3.7.

Examples of Saving Portions of a File

Key Sequence

Result

:.,12w newfile

Saves lines from where the cursor currently is to line 12 in a file named newfile

:2, 5w newfile

Saves lines 2 to 5 in a file named newfile

:12, $w newfile

Saves lines from 12 to the end of the file in a file named newfile


Inserting and Deleting

Changing existing text is simple enough if there is already text there. Inserting, however, allows you to add to the text already there, and is the mode you want to go into when starting a new file. When working within a line, you can choose to insert or append, as well as open a new line above or below the current one. Table 3.8 lists the possibilities.

Keys to Enter Input Mode

Key Sequence

Result

a

Inserts text after cursor (append)

A

Inserts text at the end of the current line

i

Inserts text before cursor

o

Opens a new line below the cursor

O

Opens a new line above the cursor

s

Removes the current letter and places you in insert mode—this is known as the "substitute" command

S

Substitute mode for the whole line


Regardless of the method by which you enter insert mode, the means by which you leave this mode is by pressing Esc.

Deleting text is accomplished by pressing x to delete a single character. It can also be preceded by a number to indicate how many characters to delete. For example:

16x

will delete the next 16 characters. To delete the character before the cursor, substitute the X command in place of x.

If you want to delete something other than characters, you can use the d (delete) command with a sequence indicating what you want to delete. Table 3.9 lists the possibilities.

Key Sequences for Deletion

Key Sequence

Result

d$

Deletes from here to the end of the line

d)

Deletes the remainder of the sentence

d}

Deletes the remainder of the paragraph

d0

Deletes from here to the beginning of the line

db

Deletes the previous word

dl

Deletes a letter

7dl

Deletes seven letters

dw

Deletes a word

7dw

Deletes four words—dw will not only delete the word, but also deletes the space after the word. To delete only to the end of a word, use de instead.


Navigating Screens

All of the discussion thus far has been about changing text that appears on the screen. The vi editor shows 23 lines within a screen. If your file exceeds 23 lines, as a great many will, you have a number of screens that you can work with. For an analogy, think of viewing screens one at a time when using more or less commands.

Table 3.10 shows the methods of navigating between multiple screens.

Key Sequences for Moving Between Screens

Key Sequence

Result

Ctrl+F

Move forward one screen

Ctrl+B

Move backward one screen

Ctrl+D

Move forward one-half screen

Ctrl+U

Move backward one-half screen

Ctrl+E

Scroll the screen up one line

Ctrl+Y

Scroll the screen down one line

H

Move to the top line of the screen

L

Move to the last line of the screen

M

Move to the middle line of the screen


NOTE

You can use numbers before each of these operations as well. 7H moves the cursor seven lines below the top line on the screen, and 7L moves the cursor seven lines above the last line on the screen.

Searching for Text

Another method of moving through the file besides using navigational keys is to perform a search. You can search the file for string values, and the screen containing the first occurrence of that string will become your current view of the file.

Searches are initiated by pressing the slash key (/) and entering the string value to search for. As you enter the search text sequence, the editor will move through the file looking for a match.

When you have entered the search string, press Enter to signify that you are done. All searches automatically begin at the top of the document. To move the cursor to the next instance, use the n command (for next). To move backward through the file, use the N command.

Two characters can be used with the search to specify where the located text must reside:

  • ^ to signify that the text must be at the start of the line

  • $ to signify that the text must be at the end of the line

For example, to find the string "is" only if these two characters are the last two characters on the line, the search syntax would be

/is$

You can also use many of the wildcard options present in grep and similar utilities:

  • \ to ignore the following character's special value

  • [] to find multiple values

  • \< to find matches at the beginning of a word

If you need to find values and change them, you can do so using the substitute command (s), with syntax that resembles sed:

:first_line, last_line s/old string/new string/

For example, to change all occurrences of "speed" to "pace" in lines between the first and thousandth, the command is

:1,1000 s/speed/pace/

Copying Text

Text can be copied into the buffer to be reused from one part of the file to another or moved. As simplistic as it sounds, when you copy text, you leave the original where it is and make a duplicate elsewhere. However, when you move text, you take it from one location in the file and place it in another. Whether you are copying or moving, the p command is always the counterpart of the operation; standing for print/put/place, it completes the operation.

Unfortunately, the "c" mnemonic had already been used for change when vi was being created and there weren't a whole lot of other good choices left. Given that, Bill Joy chose to use y for yank. Table 3.11 shows a series of key sequences that can be used for copying text.

Key Sequences for Copying Text

Key Sequence

Result

y$

Yanks from here to the end of the line

y)

Yanks the remainder of the sentence

y}

Yanks the remainder of the paragraph

y0

Yanks from here to the beginning of the line

yb

Yanks the previous word or part of a word

yl

Yanks a single letter

7yl

Yanks the next seven letters

yw

Yanks a single word

7yw

Yanks the next seven words

yy

Yanks an entire line

7yy

Yanks seven lines

Y

The same as y$


To do a copy operation, you move to the desired location in the file where the text should go, and then use the p command. To do a move operation, delete the text after yanking it, and then move to the desired location and use the p command to place the file where you want it.

Other Operations

If there is one single vi command you should commit to memory, it is u—the undo command. This command will undo the previous action, and only the previous action. It has a counterpart—U—which will do all previous actions to the current line. It is important to note, however, that U will only buffer changes for one line (the current one); this prevents you from making changes to four lines and then moving to the first and undoing them.

NOTE

If you mess up four lines and cannot put back in the first line what was changed, your only salvation is to exit the file without saving.

So many of the operations discussed in this section revolve around line numbers—you can move to a particular line by specifying its number, you can save only specific lines, and so on—that it is often helpful to have the lines numbered as you view them. Turning on line numbering in vi is accomplished by first going to command mode with a colon (:)(sometimes called colon mode; this will move the cursor to the bottom of the screen), and then entering the command set number followed by Enter. This will turn on line numbering.

The numbers appear only within the editor, just as if you were viewing them with the nl command, and are not saved out with the file. Incidentally, set number can be abbreviated as set nu. If you only want to see the number of the line you are currently on, you can press Ctrl+G, and the line number (as well as the total number of lines within the file) will appear at the bottom of the screen.

If you need to run an external command while in the editor, you can do so by using the syntax

:!{command}

For example, to see a list of files in the current directory while working in vi, the command would be

:!ls -l

This will show the listing, then prompt you to press Return (Enter) to go back to the file you are working within.

If you need to copy the contents of another file into this one, you can do so by using the syntax

:r {filename}

For example, to bring the contents of a file named first into this file, the command is

:r first

This inserts the text from the other file directly into the location in this file where the cursor resides.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020