Editing the UNIX Way

You've learned about how to manipulate your files and even peek inside at your leisure, but now it's time to learn the key UNIX tool for creating and editing files: vi.

Task 10.1: How to Start and Quit vi

You may have noticed that many of the UNIX commands covered so far have one characteristic in common. They all do their work, display their results, and quit. Among the few exceptions are more and pg, in which you work within the specific program environment until you have viewed the entire contents of the file being shown or until you quit. The vi editor is another program in this small category of environments, programs that you move in and use until you explicitly tell the program to quit.


Where did vi get its name? It's not quite as interesting as some of the earlier, more colorful command names. The vi command is so named because it's the visual interface to the ex editor. It was written by Bill Joy while he was at the University of California at Berkeley.


Before you start vi for the first time, you must learn about two aspects of its behavior. The first is that vi is a modal editor. A mode is like an environment. Different modes in vi interpret the same key differently. For example, if you're in insert mode, typing a adds an a to the text, whereas in command mode, typing a puts you in insert mode because a is the key abbreviation for the append command. If you ever get confused about what mode you're in, press the Escape key on your keyboard. Pressing Escape always returns you to the command mode (and if you're already in command mode, it simply beeps to remind you of that fact).

When you are in command mode, you can manage your document; this includes the capability to change text, rearrange it, and delete it. Insert mode is when you are adding text directly into your document from the keyboard.

In vi, the Return key is a specific command (meaning to move to the beginning of the next line). As a result, you never need to press Return to have vi process your command.


emacs is a modeless editor. In emacs, the A key always adds the letter a to the file. You indicate all commands in emacs by holding down the Control key while pressing the command key; for example, Control-C deletes a character.


The second important characteristic of vi is that it's a screen-oriented program. It must know what kind of terminal, computer, or system you are using to work with UNIX. This probably won't be a problem for you because most systems are set up so that the default terminal type matches the terminal or communications program you're using. In this hour, you learn how to recognize when vi cannot figure out what terminal you're using and what to do about it.

You can start vi in various ways, and you learn about lots of helpful alternatives later this hour. Right now, you learn the basics. The vi command, by itself, starts the editor, ready for you to create a new file. The vi command with a filename starts vi with the specified file so that you can modify that file immediately.

Let's get started!

  1. To begin, enter vi at the prompt. If all is working well, the screen will clear, the first character on each line will become a tilde (~), and the cursor will be sitting at the upper-left corner of the screen:

        % vi
    _
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    

    Type a colon. Doing so moves the cursor to the bottom of the screen and replaces the last tilde with the colon:

    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    :_
    

    Type q and press the Return key, and you should be back at the shell prompt:

    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    :q
    %
    

I'm going to show you only the portion of the screen that is relevant to the command being discussed for vi, rather than show you the entire screen each time. When the full screen is required to explain something, it will show up. A smooth edge will indicate the edge of the screen, and a jagged edge will indicate that the rest of the display has been omitted.


  1. If that operation worked without a problem, skip to instruction 3. If the operation did not work, you received the unknown-terminal-type error message. You might see this on your screen:

    % vi
    "unknown": Unknown terminal type
    I don't know what type of terminal you are on. All I have is "unknown"
    [using open mode]
    _
    

    Alternatively, you might see this:

    % vi
    Visual needs addressible cursor or upline capability
    :
    

    Don't panic. You can fix this problem. The first step is to get back to the shell prompt. To do this, do exactly what you did in instruction 1: type :q followed by the Return key. You should then see this:

    % vi
    "unknown": Unknown terminal type
    I don't know what type of terminal you are on. All I have is "unknown"
    [using open mode]
    :q
    %
    

    The problem here is that vi needs to know the type of terminal you're using, but it can't figure that out on its own. Therefore, you need to tell the operating system by setting the TERM environment variable. If you know what kind of terminal you have, use the value associated with the terminal; otherwise, try the default of vt100:

    % setenv TERM vt100
    							

    If you have the $ prompt, which means you're using the Bourne shell (sh) or Korn shell (ksh), rather than the C shell (csh), try this:

    $ TERM=vt100 ; export TERM
    							

    Either way, you can now try entering vi again, and it should work.

    If it does work, append the command (whichever of these two commands was successful for you) to your .login file if you use csh, or to .profile if you use sh or ksh. You can do this by entering whichever of the following commands is appropriate for your system:

    % echo "setenv TERM vt100" >> .login
    							

    or

    								$ echo "TERM=vt100 ; export TERM" >> .profile
    							

    This way, the next time you log in, the system will remember what kind of terminal you're using.

vi and other screen commands use a UNIX package called curses to control the screen. Like most UNIX applications, curses was not designed for a specific configuration; instead, it is designed to be device independent. Therefore, to work on a specific device, you need to give it some additional information—in this case, the terminal type.

If vt100 didn't work, it's time to talk with your system administrator about the problem or to call your UNIX vendor to find out what the specific value should be. If you are connected through a modem or other line and you actually are using a terminal emulator or communications package, you might also try using ansi as a TERM setting. If that fails, call the company that makes your software and ask the company what terminal type the communications program is emulating.


  1. Great! You have successfully launched vi, seen what it looks like, and even entered the most important command: the quit command. Now create a simple file and start vi so that it shows you the contents of the file:

    % ls -l > demo
    % vi demo
    								total 29
    drwx------ 2 taylor        512 Nov 21 10:39 Archives/
    drwx------  3 taylor        512 Dec  3 02:03 InfoWorld/
    drwx------  2 taylor       1024 Dec  3 01:43 Mail/
    drwx------  2 taylor        512 Oct  6 09:36 News/
    drwx------  4 taylor        512 Dec  2 22:08 OWL/
    -rw-rw----  1 taylor        126 Dec  3 16:34 awkscript
    -rw-rw----  1 taylor        165 Dec  3 16:42 bigfiles
    drwx------  2 taylor        512 Oct 13 10:45 bin/
    -rw-rw----  1 taylor          0 Dec  3 22:26 demo
    -rw-rw----  1 taylor      12556 Nov 16 09:49 keylime.pie
    -rw-rw----  1 taylor       8729 Dec  2 21:19 owl.c
    -rw-rw----  1 taylor        199 Dec  3 16:11 sample
    -rw-rw----  1 taylor        207 Dec  3 16:11 sample2
    drwx------  2 taylor        512 Oct 13 10:45 src/
    drwxrwx---  2 taylor        512 Nov  8 22:20 temp/
    -rw-rw----  1 taylor        582 Nov 27 18:29 tetme
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    "demo" 17 lines, 846 characters
    

    You can see that vi reads the file specified on the command line. In this example, my file is 17 lines long, but my screen can hold 25 lines. To show that some lines lack any text, vi uses the tilde on a line by itself. Finally, note that, at the bottom, the program shows the name of the file, the number of lines it found in the file, and the total number of characters.

    Type :q again to quit vi and return to the command line for now. When you type the colon, the cursor will flash down to the bottom line and wait for the q as it did before.

    You have learned the most basic command in vi—the :q command—and survived the experience. It's all downhill from here.

Task 10.2: Simple Cursor Motion in vi

Getting to a file isn't much good if you can't actually move around in it. Now you will learn how to use the cursor control keys in vi. To move left one character, type h. To move up, type k. To move down, type j, and to move right a single character, type l (lowercase L). You can move left one character by pressing the Backspace key, and you can move to the beginning of the next line with the Return key.


  1. Launch vi again, specifying the demo file:

    % vi demo
    								total 29
    drwx------  2 taylor        512 Nov 21 10:39 Archives/
    drwx------  3 taylor        512 Dec  3 02:03 InfoWorld/
    drwx------  2 taylor       1024 Dec  3 01:43 Mail/
    drwx------  2 taylor        512 Oct  6 09:36 News/
    drwx------  4 taylor        512 Dec  2 22:08 OWL/
    -rw-rw----  1 taylor        126 Dec  3 16:34 awkscript
    -rw-rw----  1 taylor        165 Dec  3 16:42 bigfiles
    drwx------  2 taylor        512 Oct 13 10:45 bin/
    -rw-rw----  1 taylor          0 Dec  3 22:26 demo
    -rw-rw----  1 taylor      12556 Nov 16 09:49 keylime.pie
    -rw-rw----  1 taylor       8729 Dec  2 21:19 owl.c
    -rw-rw----  1 taylor        199 Dec  3 16:11 sample
    -rw-rw----  1 taylor        207 Dec  3 16:11 sample2
    drwx------  2 taylor        512 Oct 13 10:45 src/
    drwxrwx---  2 taylor        512 Nov  8 22:20 temp/
    -rw-rw----  1 taylor        582 Nov 27 18:29 tetme
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    "demo" 17 lines, 846 characters
    

    You should see the cursor sitting on top of the t in total on the first line or perhaps flashing underneath the t character. Perhaps you have a flashing-box cursor or one that shows up in a different color. In any case, that's your starting spot in the file.

  2. Type h once to try to move left. The cursor stays in the same spot, and vi beeps to remind you that you can't move left any farther on the line. Try the k key to try to move up; the same thing will happen.

    Now try typing j to move down a character:

    total 29
    drwx------  2 taylor        512 Nov 21 10:39 Archives/
    drwx------  3 taylor        512 Dec  3 02:03 InfoWorld/
    drwx------  2 taylor       1024 Dec  3 01:43 Mail/
    

    Now the cursor is on the d directory indicator of the second line of the file.

    Type k to move back up to the original starting spot.

  3. Using the four cursor-control keys—the h, j, k, and l keys—move around in the file for a little bit until you are comfortable with what's happening on the screen. Now try using the Backspace and Return keys to see how they help you move around.

  4. Move to the middle of a line:

    total 29
    drwx------  2 taylor        512 Nov 21 10:39 Archives/
    drwx------  3 taylor        512 Dec  3 02:03 InfoWorld/
    drwx------  2 taylor       1024 Dec  3 01:43 Mail/
    

    Here, I'm at the middle digit in the file size of the second file in the listing. Here are a couple of new cursor motion keys: the 0 (zero) key moves the cursor to the beginning of the line, and $ moves it to the end of the line. First, I type 0:

    total 29
    drwx------  2 taylor        512 Nov 21 10:39 Archives/
    drwx------  3 taylor        512 Dec  3 02:03 InfoWorld/
    drwx------  2 taylor       1024 Dec  3 01:43 Mail/
    

    Now I type $ to move to the end of the line:

    total 29
    drwx------  2 taylor        512 Nov 21 10:39 Archives/
    drwx------  3 taylor        512 Dec  3 02:03 InfoWorld/
    drwx------  2 taylor       1024 Dec  3 01:43 Mail/
    
  5. If you have arrow keys on your keyboard, try using them to see whether they work the same way that the h, j, k, and l keys work. If the arrow keys don't move you about, they might have shifted you into insert mode. If you type characters and they're added to the file, you need to press the Escape key (or Esc, depending on your keyboard) to return to command mode. Let's wrap this up by leaving this edit session. Because vi now knows that you have modified the file, it will try to ensure that you don't quit without saving the changes:

    ~
    ~
    :q
    No write since last change (:quit! overrides)
    
    
    Use :q! (shorthand for :quit) to quit without saving the changes.
    

    Stay in this file for the next task if you'd like, or use :q to quit.

In general, if you try to use a colon command in vi and the program complains that it might do something bad, try the command again, followed by an exclamation point. I like to think of this as saying, “Do it anyway!”


Moving about a file using these six simple key commands is, on a small scale, much like the entire process of using the vi editor when working with files. Stick with these simple commands until you're comfortable moving around, and you will be well on your way to becoming proficient using vi.


Task 10.3: Moving by Words and Pages

Earlier, in the description of the emacs editor, I commented that because it's always in insert mode, all commands must include the Control key. Well, it turns out that vi has its share of control-key commands, commands that require you to hold down the Control key and press another key. In this section, you learn about Ctrl-f, Ctrl-b, Ctrl-u, and Ctrl-d. These move you forward or backward a screen, and up or down half a screen of text, respectively.


I toss a few more commands into the pot, too: w moves you forward word by word, b moves you backward word by word, and the uppercase versions of these two commands have very similar, but not identical, functions.

  1. To see how this works, you need to create a file that is longer than the size of your screen. An easy way to do this is to save the output of a common command to a file over and over until the file is long enough. The system I use has lots of users, so I needed to use the who command just once. You might have to append the output of who to the big.output file a couple of times before the file is longer than 24 lines. (You can check using wc, of course.)

    % who > big.output; wc -l big.output
       40
    % vi big.output
    								leungtc  ttyrV   Dec  1 18:27   (magenta)
    tuyinhwa ttyrX   Dec  3 22:38   (expert)
    hollenst ttyrZ   Dec  3 22:14   (dov)
    brandt   ttyrb   Nov 28 23:03   (age)
    holmes   ttyrj   Dec  3 21:59   (age)
    yuxi     ttyrn   Dec  1 14:19   (pc115)
    frodo    ttyro   Dec  3 22:01   (mentor)
    labeck   ttyrt   Dec  3 22:02   (dov)
    chenlx2  ttyru   Dec  3 21:53   (mentor)
    leungtc  ttys0   Nov 28 15:11   (gold)
    chinese  ttys2   Dec  3 22:53   (excalibur)
    cdemmert ttys5   Dec  3 23:00   (mentor)
    yuenca   ttys6   Dec  3 23:00   (mentor)
    janitor  ttys7   Dec  3 18:18   (age)
    mathisbp ttys8   Dec  3 23:17   (dov)
    janitor  ttys9   Dec  3 18:18   (age)
    cs541    ttysC   Dec  2 15:16   (solaria)
    yansong  ttysL   Dec  1 14:44   (math)
    mdps     ttysO   Nov 30 19:39   (localhost)
    md       ttysU   Dec  2 08:45   (muller)
    jac      ttysa   Dec  3 18:18   (localhost)
    eichsted ttysb   Dec  3 23:21   (pc1)
    sweett   ttysc   Dec  3 22:40   (dov)
    "big.output" 40 lines, 1659 characters
    

    Because I have only a 25-line display and the output is 40 lines long (you can see that on the status line at the bottom), there is more information in this file than the screen can display at once.

  2. To see the next screenful, press Ctrl-f.

    I press Control-f and get the following output:

    								eichsted ttysb   Dec  3 23:21   (pc1)
    sweett   ttysc   Dec  3 22:40   (dov)
    wellman  ttysd   Dec  3 23:01   (dov)
    tuttleno ttyse   Dec  3 23:03   (indyvax)
    wu       ttysf   Dec  3 23:10   (term01)
    daurismj ttysg   Dec  3 23:10   (dov)
    cs414    ttysh   Dec  3 23:12   (xds)
    cq       ttysi   Dec  3 23:13   (expert)
    cdemmert ttysk   Dec  3 22:37   (xsun22)
    jrlee    ttysn   Dec  3 22:53   (mac1)
    fitzgejs ttyso   Dec  3 23:18   (dov)
    doerrhb  ttysp   Dec  3 23:20   (dov)
    cdemmert ttysq   Dec  3 23:00   (xsun22)
    frazierw ttysr   Dec  3 23:01   (dov)
    buckeye  ttyss   Dec  3 23:20   (mac2)
    mtaylor  ttyst   Dec  3 23:22   (dov)
    look     ttysu   Dec  3 23:12   (age)
    janitor  ttysw   Dec  3 18:29   (age)
    ajones   ttysx   Dec  3 23:23   (rass)
    ~
    ~
    ~
    ~
    

    Notice that the entire screen was rewritten and that the familiar tilde characters have popped up again to let me know that I have reached the end of the file.

    By default, vi has a two-line overlap when you move from screen to screen. If you look carefully, you can see that both eichsted and sweett show up on both screens of data. This doesn't mean that they appear twice in the file; rather, vi is trying to help me not get lost while I wander through the file.

  3. Now, what do you think will happen if I press Control-u?

    								leungtc  ttys0   Nov 28 15:11   (gold)
    chinese  ttys2   Dec  3 22:53   (excalibur)
    cdemmert ttys5   Dec  3 23:00   (mentor)
    yuenca   ttys6   Dec  3 23:00   (mentor)
    janitor  ttys7   Dec  3 18:18   (age)
    mathisbp ttys8   Dec  3 23:17   (dov)
    janitor  ttys9   Dec  3 18:18   (age)
    cs541    ttysC   Dec  2 15:16   (solaria)
    yansong  ttysL   Dec  1 14:44   (math)
    mdps     ttysO   Nov 30 19:39   (localhost)
    md       ttysU   Dec  2 08:45   (muller)
    jac      ttysa   Dec  3 18:18   (localhost)
    eichsted ttysb   Dec  3 23:21   (pc1)
    sweett   ttysc   Dec  3 22:40   (dov)
    wellman  ttysd   Dec  3 23:01   (dov)
    tuttleno ttyse   Dec  3 23:03   (indyvax)
    wu       ttysf   Dec  3 23:10   (term01)
    daurismj ttysg   Dec  3 23:10   (dov)
    cs414    ttysh   Dec  3 23:12   (xds)
    cq       ttysi   Dec  3 23:13   (expert)
    cdemmert ttysk   Dec  3 22:37   (xsun22)
    jrlee    ttysn   Dec  3 22:53   (mac1)
    fitzgejs ttyso   Dec  3 23:18   (dov)
    

    The command has moved me up half a screen. Notice where eichsted and sweett are now. Instead of the text being replaced at once, as when I used Control-f, the text was scrolled downward a line at a time, each new line being added as the program went along. The Control-u command might work either way—one line or an entire screen at a time—for you.

  4. Now it's time to try moving around in this file word by word. Type the w key once to see what happens:

    leungtc  ttys0   Nov 28 15:11   (gold)
    chinese  ttys2   Dec  3 22:53   (excalibur)
    cdemmert ttys5   Dec  3 23:00   (mentor)
    

    Now type w six times more, noting that the cursor stops three times in the field to indicate what time the user logged in to the system (15:11 in this listing). Now your cursor should be sitting on the parenthesized field:

    leungtc  ttys0   Nov 28 15:11   (gold)
    chinese  ttys2   Dec  3 22:53   (excalibur)
    cdemmert ttys5   Dec  3 23:00   (mentor)
    
  5. It's time to move backward. Type b a few times; your cursor moves backward to the beginning of each word.

    What happens if you try to move backward and you're already on the first word, or if you try to move forward with the w command and you're already on the last word of the line? Let's find out.

  6. Using the various keys you've learned, move back to the beginning of the line that starts with leungtc, which you used in instruction 4:

    								leungtc  ttys0   Nov 28 15:11   (gold)
    chinese  ttys2   Dec  3 22:53   (excalibur)
    cdemmert ttys5   Dec  3 23:00   (mentor)
    

    This time, type W (uppercase W, not lowercase w) to move through this line. Can you see the difference? Notice what happens when you hit the time field and the parenthesized words. Instead of typing w seven times to move to the left parenthesis before gold, you can type W only five times.

  7. Try moving backward using the B command. Notice that the B command differs from the b command the same way in which the W command differs from the w command.

Moving about by words, both forward and backward, being able to zip through half screens or full screens at a time, and being able to zero in on specific spots with the h, j, k, and l cursor-motion keys give you quite a range of motion. Practice using these commands in various combinations to get your cursor to specific characters in your sample file.


Task 10.4: Inserting Text into the File Using i, a, o, and 0

Being able to move around in a file is useful. The real function of an editor, however, is to enable you to easily add and remove—in editor parlance, insert and delete—information. The vi editor has a special insert mode, which you must use in order to add to the contents of the file. There are four ways to shift into insert mode, and you learn about all of them in this unit.


The first way to switch to insert mode is to type the letter i, which, mnemonically enough, inserts text into the file. The other commands that accomplish more or less the same thing are a, to append text to the file; o, to open a line below the current line; and O, to open a line above the current line.

  1. For this task, you need to start with a clean file, so quit from the big.output editing session and start vi again, this time specifying a nonexistent file called buckaroo:

    % vi buckaroo
    _
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    "buckaroo" [New file]
    

    Notice that vi reminds you that this file doesn't exist; the bottom of the screen says New file, instead of indicating the number of lines and characters.

  2. Now it's time to try using insert mode. Try to insert a k into the file by typing k once:

    _
    ~
    ~
    ~
    

    The system beeps at you because you haven't moved into insert mode yet, and the k still has its command meaning of moving down a line (and of course, there isn't another line yet).

    Type i to move into insert mode, and then type k again:

    k_
    ~
    ~
    ~
    

    There you go! You've added a character to the file.

  3. Press the Backspace key, which will move the cursor over the letter k:

    								k
    ~
    ~
    ~
    

    Now see what happens when you press Escape to leave insert mode and return to the vi command mode:

    _
    ~
    ~
    ~
    

    Notice that the k vanished when you pressed Escape. That's because vi only saves text you've entered to the left of or above the cursor, not the letter the cursor is resting on.

  4. Now move back into insert mode by typing i, and enter a few sentences from a favorite book of mine.

    								"He's not even here," went the conservation.
    								"Banzai."
    								"Where is he?"
    								"At a hotpsial in El paso."
    								"What? Why werent' we informed? What's wrong with him?"_
    ~
    ~
    

    I've deliberately left some typing errors in the text here. Fixing them will demonstrate some important features of the vi editor. If you fixed them as you went along, that's okay, and if you added errors of your own, that's okay too!

    Press Escape to leave insert mode. Press Escape a second time to ensure that it worked; remember that vi beeps to remind you that you're already in command mode.

Movie buffs perhaps will recognize that the text used in this hour comes from the book Buckaroo Banzai. The film The Adventures of Buckaroo Banzai Across the Eighth Dimension is based on this very fun book.


  1. Use the cursor motion keys (h, j, k, and l) to move the cursor to any point on the first line:

    "He's not even here," went the conservation.
    "Banzai."
    "Where is he?"
    "At the hotpsial in El paso."
    "What? Why werent' we informed? What's wrong with him?"
    ~
    ~
    

    It turns out that I forgot a line of dialog between the line I'm on and the word Banzai. One way to enter the line would be to move to the beginning of the line "Banzai.", insert the new text, and press Return before pressing Escape to quit insert mode. But vi has a special command—o—to open a line immediately below the current line for inserting text. Type o and follow along:

    "He's not even here," went the conservation.
    _
    "Banzai."
    "Where is he?"
    "At the hotpsial in El paso."
    "What? Why werent' we informed? What's wrong with him?"
    ~
    ~
    

    Now type the missing text:

    "He's not even here," went the conservation.
    "Who?"_
    "Banzai."
    "Where is he?"
    "At the hotpsial in El paso."
    "What? Why werent' we informed? What's wrong with him?"
    ~
    ~
    

    That's it. Press Escape to return to command mode.

  2. The problem with the snippet of dialog we're using is that there's no way to figure out who is talking. Adding a line above this dialog helps identify the speakers. Again, use cursor motion keys to place the cursor on the top line:

    "He's not _even here," went the conservation.
    "Who?"
    "Banzai."
    "Where is he?"
    "At the hotpsial in El paso."
    "What? Why werent' we informed? What's wrong with him?"
    ~
    ~
    

    Now you face a dilemma. You want to open a line for new text, but you want the line to be above the current line, not below it. It happens that vi can do that too. Instead of using the o command, use its big brother O instead. When I type O, here's what I see:

    								_
    "He's not even here," went the conservation.
    "Who?"
    "Banzai."
    "Where is he?"
    "At the hotpsial in El paso."
    "What? Why werent' we informed? What's wrong with him?"
    ~
    ~
    

    Type the new sentence and then press Escape.

    								I found myself stealing a peek at my own watch and overheard
    								General Catbird's
    								aide give him the latest._
    "He's not even here," went the conservation.
    "Who?"
    "Banzai."
    "Where is he?"
    "At the hotpsial in El paso."
    "What? Why werent' we informed? What's wrong with him?"
    ~
    ~
    

    Now the dialog makes a bit more sense. The conversation, overheard by the narrator, takes place between the general and his aide.

  3. I missed a couple of words in one of the lines, so the next task is to insert them. Use the cursor keys to move the cursor to the fifth line, just after the word Where:

    I found myself stealing a peek at my own watch and overheard
    General Catbird's
    aide give him the latest.
    "He's not even here," went the conservation.
    "Who?"
    "Banzai."
    "Where__is he?"
    "At the hotpsial in El paso."
    "What? Why werent' we informed? What's wrong with him?"
    ~
    ~
    

    At this juncture, I need to add the words the hell to make the sentence a bit stronger (and correct). I can use i to insert the text, but then I end up with a trailing space. Instead, I can add text immediately after the current cursor location by using the a command to append, or insert, the information. When I type a, the cursor moves one character to the right:

    I found myself stealing a peek at my own watch and overheard
    General Catbird's
    aide give him the latest.
    "He's not even here," went the conservation.
    "Who?"
    "Banzai."
    "Where is he?"
    "At the hotpsial in El paso."
    "What? Why werent' we informed? What's wrong with him?"
    ~
    ~
    

    Here's where vi can be difficult to use. I'm in insert mode, but there's no way for me to know that. When I type the letters I want to add, the screen shows that they are appended, but what if I thought I was in insert mode when I actually was in command mode? One trick I could use to ensure I'm in insert mode is to type the command a second time. If the letter a shows up in the text, I simply would backspace over it; now I would know that I'm in append mode. When I'm done entering the new characters, and I'm still in insert mode, here's what my screen looks like:

    I found myself stealing a peek at my own watch and overheard
    General Catbird's
    aide give him the latest.
    "He's not even here," went the conservation.
    "Who?"
    "Banzai."
    "Where the hell is he?"
    "At the hotpsial in El paso."
    "What? Why werent' we informed? What's wrong with him?"
    ~
    ~
    

    Notice that the cursor always stayed on the i in is throughout this operation. Press Escape to return to command mode. Notice that the cursor finally hops off the i and moves left one character.

To differentiate between the i and a commands, remember that the insert command always adds the new information immediately before the character that the cursor is sitting on, whereas the append command adds the information immediately to the right of the current cursor position.


  1. With this in mind, try to fix the apostrophe problem in the word werent' on the last line. Move the cursor to the n in that word:

    "Where the hell is he?"
    "At the hotpsial in El paso."
    "What? Why werent' we informed? What's wrong with him?"
    ~
    

    To add the apostrophe immediately after the current character, do you want to use the insert command (i) or the append (a) command? If you said “append,” give yourself a pat on the back! Type a to append the apostrophe:

    "Where the hell is he?"
    "At the hotpsial in El paso."
    "What? Why werent' we informed? What's wrong with him?"
    ~
    

    Type ' once and then press Escape.

  2. Quit vi using :q, and the program reminds you that you haven't saved your changes to this new file:

    ~
    ~
    No write since last change (:quit! overrides)
    

    To write the changes, you need a new command, so I'll give you a preview of a set of colon commands you learn later in this hour. Type : (the colon character), which moves the cursor to the bottom of the screen.

    ~
    ~
    :_
    							

    Now type w to write out (save) the file, and then press the Return key:

    ~
    ~
    "buckaroo" 9 lines, 277 characters
    

    It's okay to leave vi now. I'll use :q to quit, and I'm safely back at the command prompt. A quick cat confirms that the tildes were not included in the file itself:

    % cat buckaroo
    I found myself stealing a peek at my own watch and overheard
    General Catbird's
    aide give him the latest.
    "He's not even here," went the conservation.
    "Who?"
    "Banzai."
    "Where the hell is he?"
    "At the hotpsial in El paso."
    "What? Why weren't' we informed? What's wrong with him?"
    %
    

    As you can tell, the vi editor is quite powerful, and it has a plethora of commands. Just moving about and inserting text, you have learned 24 commands, as summarized in Table 10.1.

Table 10.1. Summary of vi Motion and Insertion Commands
Command Meaning
0 Move to the beginning of the line.
$ Move to the end of the line.
a Append text—enter into insert mode after the current character.
^b Back up one screen of text.
B Back up one space-delimited word.
b Back up one word.
Backspace Move left one character.
^d Move down half a page.
Escape Leave insert mode, and return to command mode.
^f Move forward one screen of text.
h Move left one character.
i Insert text—enter into insert mode before the current character.
j Move down one line.
k Move up one line.
l Move right one character.
O Open a new line for inserting text above the current line.
o Open a new line for inserting text below the current line.
Return Move to the beginning of the next line.
^u Move up half a page.
W Move forward one space-delimited word.
w Move forward one word.
:w Write the file to disk.
:q Quit vi and return to the UNIX system prompt.
:q! Quit vi and return to the UNIX system prompt, throwing away any changes made to the file.

In this table, I use the simple shorthand notation introduced in Hour 7, “Looking into Files.” UNIX users often use a caret followed by a character instead of the awkward Control-c notation. Therefore, ^f has the same meaning as Control-f. Expressing this operation as ^f does not change the way it's performed: You still press and hold down the Control key, and then type f. It's just a shorter notation.


You've already learned quite a few commands, but you have barely scratched the surface of the powerful vi command!

Task 10.5: Deleting Text

You now have many of the pieces you need to work efficiently with the vi editor, to zip to any point in the file, and to add text wherever you'd like. Now you need to learn how to delete characters, words, and lines.


The simplest form of the delete command is the x command, which functions as though you were writing an X over a letter you don't want on a printed page: It deletes the character under the cursor. Type x five times, and you delete five characters. Deleting a line of text this way can be quite tedious, so vi has some alternative commands. (Are you surprised?) One command that many vi users don't know about is the D (for “delete through the end of the line”) command. Wherever you are on a line, if you type D, you immediately will delete everything after the cursor to the end of that line of text.

If there's an uppercase D command, you can just bet there's a lowercase d command too. The d delete command is the first of a set of more sophisticated vi commands which you follow with a second command that indicates what you'd like to do with the command. You already know that w and W move you forward a word in the file; they're known as addressing commands in vi. You can follow d with one of these addressing commands to specify what you want to delete. For example, to delete a word, simply type dw.

Sometimes you might get a bit overzealous and delete more than you anticipated. That's not a problem—well, not too much of a problem—because vi remembers the state of the file prior to the most recent action taken. To undo a deletion (or insertion, for that matter), use the u command. To undo a line of changes, use the U command. Be aware that once you've moved off the line in question, the U command is unable to restore it!


  1. Start vi again with the big.output file you used earlier:

    								leungtc  ttyrV   Dec  1 18:27   (magenta)
    tuyinhwa ttyrX   Dec  3 22:38   (expert)
    hollenst ttyrZ   Dec  3 22:14   (dov)
    brandt   ttyrb   Nov 28 23:03   (age)
    holmes   ttyrj   Dec  3 21:59   (age)
    yuxi     ttyrn   Dec  1 14:19   (pc)
    frodo    ttyro   Dec  3 22:01   (mentor)
    labeck   ttyrt   Dec  3 22:02   (dov)
    chenlx2  ttyru   Dec  3 21:53   (mentor)
    leungtc  ttys0   Nov 28 15:11   (gold)
    chinese  ttys2   Dec  3 22:53   (excalibur)
    cdemmert ttys5   Dec  3 23:00   (mentor)
    yuenca   ttys6   Dec  3 23:00   (mentor)
    janitor  ttys7   Dec  3 18:18   (age)
    mathisbp ttys8   Dec  3 23:17   (dov)
    janitor  ttys9   Dec  3 18:18   (age)
    cs541    ttysC   Dec  2 15:16   (solaria)
    yansong  ttysL   Dec  1 14:44   (math)
    mdps     ttysO   Nov 30 19:39   (localhost)
    md       ttysU   Dec  2 08:45   (muller)
    jac      ttysa   Dec  3 18:18   (localhost)
    eichsted ttysb   Dec  3 23:21   (pc1)
    sweett   ttysc   Dec  3 22:40   (dov)
    "big.output" 40 lines, 1659 characters
    

    Type x a few times to delete a few characters from the beginning of the file:

    								gtc  ttyrV   Dec  1 18:27   (magenta)
    tuyinhwa ttyrX   Dec  3 22:38   (expert)
    hollenst ttyrZ   Dec  3 22:14   (dov)
    brandt   ttyrb   Nov 28 23:03   (age)
    holmes   ttyrj   Dec  3 21:59   (age)
    

    Now type u to undo the last deletion:

    								ngtc  ttyrV   Dec  1 18:27   (magenta)
    tuyinhwa ttyrX   Dec  3 22:38   (expert)
    hollenst ttyrZ   Dec  3 22:14   (dov)
    brandt   ttyrb   Nov 28 23:03   (age)
    holmes   ttyrj   Dec  3 21:59   (age)
    

    If you type u again, what do you think will happen?

    								gtc  ttyrV   Dec  1 18:27   (magenta)
    tuyinhwa ttyrX   Dec  3 22:38   (expert)
    hollenst ttyrZ   Dec  3 22:14   (dov)
    brandt   ttyrb   Nov 28 23:03   (age)
    holmes   ttyrj   Dec  3 21:59   (age)
    

    The undo command alternates between the last command having happened or not having happened. To explain it a bit better, the undo command is an action unto itself, so the second time you type u, you're undoing the undo command that you just requested. Type u a few more times to convince yourself that this is the case.

  2. It's time to make some bigger changes to the file. Type dw twice to delete the current word and the next word in the file. It should look something like this after using the first dw:

    								ttyrV   Dec  1 18:27   (magenta)
    tuyinhwa ttyrX   Dec  3 22:38   (expert)
    hollenst ttyrZ   Dec  3 22:14   (dov)
    brandt   ttyrb   Nov 28 23:03   (age)
    holmes   ttyrj   Dec  3 21:59   (age)
    

    Then it should look like this after using the second dw:

    								Dec  1 18:27   (magenta)
    tuyinhwa ttyrX   Dec  3 22:38   (expert)
    hollenst ttyrZ   Dec  3 22:14   (dov)
    brandt   ttyrb   Nov 28 23:03   (age)
    holmes   ttyrj   Dec  3 21:59   (age)
    

    Type u. You see that you can undo only the most recent command. At this point, though, because I haven't moved from the line I'm editing, the U, or undo-a-line-of-changes, command will restore the line to its original splendor:

    								leungtc  ttyrV   Dec  1 18:27   (magenta)
    tuyinhwa ttyrX   Dec  3 22:38   (expert)
    hollenst ttyrZ   Dec  3 22:14   (dov)
    brandt   ttyrb   Nov 28 23:03   (age)
    holmes   ttyrj   Dec  3 21:59   (age)
    
  3. Well, in the end, I really don't want to see some of these folk. Fortunately, I can change the contents of this file using the dd command to delete lines. When you're using one of these two-letter commands, repeating the letter means to apply the command to the entire line. What if I want to delete the entries for chinese and janitor, both of which are visible on this screen?

    The first step is to use the cursor keys to move down to any place on the line for the chinese account, about halfway down the screen:

    chenlx2  ttyru   Dec  3 21:53   (mentor)
    leungtc  ttys0   Nov 28 15:11   (gold)
    chinese  ttys2   Dec  3 22:53   (excalibur)
    cdemmert ttys5   Dec  3 23:00   (mentor)
    yuenca   ttys6   Dec  3 23:00   (mentor)
    janitor  ttys7   Dec  3 18:18   (age)
    mathisbp ttys8   Dec  3 23:17   (dov)
    

    If your cursor isn't somewhere in the middle of this line, move it so that you too are not at an edge.

    I had planned to remove this line completely, but perhaps I'd rather just remove the date, time, and name of the system (in parentheses) instead. To accomplish this, I don't need to type dw a bunch of times, or even x a lot of times, but rather just D to delete through the end of the line:

    chenlx2  ttyru   Dec  3 21:53   (mentor)
    leungtc  ttys0   Nov 28 15:11   (gold)
    chinese  ttys2  _
    cdemmert ttys5   Dec  3 23:00   (mentor)
    yuenca   ttys6   Dec  3 23:00   (mentor)
    janitor  ttys7   Dec  3 18:18   (age)
    mathisbp ttys8   Dec  3 23:17   (dov)
    

    Oh, that's not quite what I wanted to do. No problem, the undo command can fix it. Simply typing u restores the text I deleted:

    chenlx2  ttyru   Dec  3 21:53   (mentor)
    leungtc  ttys0   Nov 28 15:11   (gold)
    chinese  ttys2   Dec  3 22:53   (excalibur)
    cdemmert ttys5   Dec  3 23:00   (mentor)
    yuenca   ttys6   Dec  3 23:00   (mentor)
    janitor  ttys7   Dec  3 18:18   (age)
    mathisbp ttys8   Dec  3 23:17   (dov)
    
  4. The problem is that I wanted to delete the two entries chinese and janitor from the file, but I used the wrong command. Instead of using the D command, I should use dd. Typing dd once has these results:

    Dec  1 18:27    (magenta)
    tuyinhwa ttyrX   Dec  3 22:38   (expert)
    hollenst ttyrZ   Dec  3 22:14   (dov)
    brandt   ttyrb   Nov 28 23:03   (age)
    holmes   ttyrj   Dec  3 21:59   (age)
    yuxi     ttyrn   Dec  1 14:19   (pc)
    frodo    ttyro   Dec  3 22:01   (mentor)
    labeck   ttyrt   Dec  3 22:02   (dov)
    chenlx2  ttyru   Dec  3 21:53   (mentor)
    leungtc  ttys0   Nov 28 15:11   (gold)
    cdemmert ttys5   Dec  3 23:00   (mentor)
    yuenca   ttys6   Dec  3 23:00   (mentor)
    janitor  ttys7   Dec  3 18:18   (age)
    mathisbp ttys8   Dec  3 23:17   (dov)
    janitor  ttys9   Dec  3 18:18   (age)
    cs541    ttysC   Dec  2 15:16   (solaria)
    yansong  ttysL   Dec  1 14:44   (math)
    mdps     ttysO   Nov 30 19:39   (localhost)
    md       ttysU   Dec  2 08:45   (muller)
    jac      ttysa   Dec  3 18:18   (localhost)
    eichsted ttysb   Dec  3 23:21   (pc1)
    sweett   ttysc   Dec  3 22:40   (dov)
    wellman  ttysd   Dec  3 23:01   (dov)
    

    Notice that a new line of information has been pulled onto the screen at the bottom to replace the blank line you removed.

    If you try using the u command now, what happens?

    I'm almost done. A few presses of the Return key and I'm down to the entry for the janitor account. Using dd removes that line too:

    Dec  1 18:27    (magenta)
    tuyinhwa ttyrX   Dec  3 22:38   (expert)
    hollenst ttyrZ   Dec  3 22:14   (dov)
    brandt   ttyrb   Nov 28 23:03   (age)
    holmes   ttyrj   Dec  3 21:59   (age)
    yuxi     ttyrn   Dec  1 14:19   (pc)
    frodo    ttyro   Dec  3 22:01   (mentor)
    labeck   ttyrt   Dec  3 22:02   (dov)
    chenlx2  ttyru   Dec  3 21:53   (mentor)
    leungtc  ttys0   Nov 28 15:11   (gold)
    cdemmert ttys5   Dec  3 23:00   (mentor)
    yuenca   ttys6   Dec  3 23:00   (mentor)
    mathisbp ttys8   Dec  3 23:17   (dov)
    janitor  ttys9   Dec  3 18:18   (age)
    cs541    ttysC   Dec  2 15:16   (solaria)
    yansong  ttysL   Dec  1 14:44   (math)
    mdps     ttysO   Nov 30 19:39   (localhost)
    md       ttysU   Dec  2 08:45   (muller)
    jac      ttysa   Dec  3 18:18   (localhost)
    eichsted ttysb   Dec  3 23:21   (pc1)
    sweett   ttysc   Dec  3 22:40   (dov)
    wellman  ttysd   Dec  3 23:01   (dov)
    tuttleno ttyse   Dec  3 23:03   (indyvax)
    

    Each line below the one deleted moves up a line to fill in the blank space, and a new line, for tuttleno, moves up from the following screen.

  5. Now I want to return to the buckaroo file to remedy some of the horrendous typographical errors! I don't really care whether I save the changes I've just made to the file, so I'm going to use :q! to quit, discarding these changes to the big.output file. Entering vi buckaroo starts vi again:

    								I found myself stealing a peek at my own watch and overheard
    General Catbird's
    aide give him the latest.
    "He's not even here," went the conservation.
    "Who?"
    "Banzai."
    "Where the hell is he?"
    "At the hotpsial in El paso."
    "What? Why weren't' we informed? What's wrong with him?"
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    "buckaroo" 9 lines, 277 characters
    

    There are a couple fixes you can make in short order. The first is to change conservation to conversation on the third line. To move there, press the Return key twice, and then use W to zip forward until the cursor is at the first letter of the word you're editing:

    I found myself stealing a peek at my own watch and overheard
    General Catbird's
    aide give him the latest.
    "He's not even here," went the conservation.
    "Who?"
    "Banzai."
    "Where the hell is he?"
    

    Then use the dw command:

    I found myself stealing a peek at my own watch and overheard
    General Catbird's
    aide give him the latest.
    "He's not even here," went the .
    "Who?"
    "Banzai."
    "Where the hell is he?"
    

    Now enter insert mode by typing i, type the correct spelling of the word conversation, and then press Escape:

    I found myself stealing a peek at my own watch and overheard
    General Catbird's
    aide give him the latest.
    "He's not even here," went the conversation.
    "Who?"
    "Banzai."
    "Where the hell is he?"
    
  6. That's one fix. Now move down a couple of lines to fix the atrocious misspelling of hospital:

    "Banzai."
    "Where the hell is he?"
    "At the hotpsial in El paso."
    "What? Why weren't' we informed? What's wrong with him?"
    ~
    

    Again, use dw to delete the word, type i to enter insert mode, type hospital, and then press Escape. Now all is well on the line:

    "At the hospital in El paso."
    "What? Why weren't' we informed? What's wrong with him?"
    ~
    

    Well, almost all is well. The first letter of Paso needs to be capitalized. Move to it by typing w to move forward a few words:

    "Banzai."
    "Where the hell is he?"
    "At the hospital in El paso."
    "What? Why weren't' we informed? What's wrong with him?"
    ~
    
  7. It's time for a secret vi expert command! Instead of typing x to delete the letter, i to enter insert mode, P as the correct letter, and then Escape to return to command mode, you can use a much faster method to transpose case: the ~ (tilde) command. Type ~ once, and here's what happens:

    "Banzai."
    "Where the hell is he?"
    "At the hospital in El Paso."
    "What? Why weren't' we informed? What's wrong with him?"
    ~
    

    Cool, isn't it? Back up to the beginning of the word again, using the h command, and type ~ a few times to see what happens. Notice that each time you type ~, the character's case switches—transposes—and the cursor moves to the next character. Type ~ four times, and you should end up with this:

    "Banzai."
    "Where the hell is he?"
    "At the hospital in El pASO."
    "What? Why weren't' we informed? What's wrong with him?"
    ~
    

    Back up to the beginning of the word, and type ~ until the word is correct.

  8. One more slight change, and the file is fixed! Move to the last line of the file, to the extra apostrophe in the word weren't', and type x to delete the offending character. The screen should now look like this:

    I found myself stealing a peek at my own watch and overheard
    General Catbird's
    aide give him the latest.
    "He's not even here," went the conversation.
    "Who?"
    "Banzai."
    "Where the hell is he?"
    "At the hospital in El Paso."
    "What? Why weren't we informed? What's wrong with him?"
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    ~
    

    That looks great! It's time to save it for posterity. Use :wq, a shortcut that has vi write out the changes and immediately quit the program:

    ~
    ~
    ~
    "buckaroo" 9 lines, 276 characters
    %
    

Not only have you learned about the variety of deletion options in vi, but you also have learned a few simple shortcut commands: ~ to transpose case, and :wq to write out the changes and quit the program all in one step.


You should feel pleased; you're now a productive and knowledgeable vi user, and you can modify files, making easy or tough changes. Go back to your system and experiment further, modifying some of the other files. Be careful, though, not to make changes in any of your dot files (for example, .cshrc) lest you cause trouble that would be difficult to fix!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.255.127