Working with vi
Course Objectives Covered
-
Creating, Viewing, and Appending Files (3036)
-
Introduction to Linux Text Editors (3036)
-
Using Command Line Editors to Edit (3036)
-
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 "veye") 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 visualhence the "v"and interactivehence 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 crudewho 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 editoryou 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 changesyou 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 viif 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" modeoverwriting 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 savehaving clobbered too much text to undo, changed your mind, and so onyou 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 modethis 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 wordsdw 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 uthe undo command. This command will undo the previous action, and only the previous action. It has a counterpartUwhich 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 numbersyou can move to a particular line by specifying its number, you can save only specific lines, and so onthat 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.