Creating and Editing Files

One easy way to create a file is with a Unix feature called input/output redirection, as Chapter 6 explains. This sends the output of a program directly to a file, to make a new file or add to an existing one.

You’ll usually create and edit a plain-text file with a text editor program. Text editors are somewhat different than word processors.

Text Editors and Word Processors

A text editor lets you add, change, and rearrange text easily. Three popular Unix editors included with Mac OS X are vi (pronounced “vee-eye”), Pico, (“pea-co”), and Emacs (“e-max”).

You should choose an editor you’re comfortable with. vi is probably the best choice because all Unix systems have it, but Emacs is also widely available. If you’ll be doing simple editing only, Pico is a great choice. Although Pico is much less powerful than Emacs or vi, it’s a lot easier to learn. For this book, however, we’ll focus on the rudiments of vi since it’s the most widely available Unix editor, and there’s a terrific version included with Mac OS X called vim.

None of these plain text editors has the same features as popular word-processing software, but vi and Emacs are sophisticated, extremely flexible editors for all kinds of plain-text files: programs, email messages, and so on.

Tip

Of course, you can opt to use a graphical text editor such as BBEdit or TextEdit with good results too, if you’d rather just sidestep editing while within the Terminal application. If you do, try using the open command within the Terminal to launch the editor with the proper file already loaded. For example: open -e myfile.txt will open the specified file in TextEdit. One gotcha: you won’t see any dot files in the Finder.

By “plain text,” we mean a file with only letters, numbers, and punctuation characters in it (text without formatting such as point size, bold and italics, or embedded images). Unix systems use plain-text files in many places: in redirected input and output of Unix programs (see Chapter 6), as shell setup files (see Chapter 1), for shell scripts (see Chapter 10), for system configuration, and more. Text editors edit these files. When you use a word processor, though, although the screen may look as if the file is only plain text, the file probably also has hidden codes (nontext characters) in it. That’s often true even if you tell the word processor to “Save as plain text.” One easy way to check for nontext characters in a file is by reading the file with less; look for characters in reversed colors, codes such as <36>, and so on.

If you need to do word processing—making documents, envelopes, and so on—your best bet is to work with a program designed for that purpose such as Microsoft Office X, or Panther’s all-powerful TextEdit, which can read and write Word files.

The vi Text Editor

The vi editor, originally written by Bill Joy at the University of California, Berkeley, is easy to use once you master the fundamental concept of a modal editor. Mac OS X actually includes a version of vi that has many useful new features, called vim. In this section, we cover only its basic commands, but if you become a vi master, you’ll enjoy vim’s powerful extensions.

Modes can be best explained by thinking about your car stereo. When you have a tape in (or a CD), the “1” button does one task, but if you are listening to the radio, the very same button does something else (perhaps jump to preprogrammed station #1). The vi editor is exactly the same: in Command mode, i jumps you into Insert mode, but in Insert mode it actually inserts an “i” into the text itself. The handiest key on your keyboard while you’re learning vi is unquestionably ESC: if you’re in Insert mode, ESC will move you back into Command mode, and if you’re in Command mode, it’ll beep to let you know that all is well. Use ESC often, until you’re completely comfortable keeping track of what mode you’re in.

Start vi by typing its name; the argument is the filename you want to create or edit. For instance, to edit your .profile setup file, you would cd to your home directory and enter:

$ vi .profile

The terminal fills with a copy of the file (and, because the file is short, some blank lines too, as denoted by the ~ at the beginning of the line), as shown in Figure 4-1.

vi display while editing

Figure 4-1. vi display while editing

The bottom row of the window is the status line, which indicates what file you’re editing: ".profile” 8L, 164C. This indicates that the file has eight lines with a total of 164 characters. Quit the program by typing :q and pressing Return while in Command mode.

vi tour

Let’s take a tour through vi. In this example, you’ll make a new file. You can call the file anything you want, but it’s best to use only letters and numbers in the filename. For instance, to make a file named sample, enter the command vi sample. Let’s start our tour now.

  1. Your screen should look something like Figure 4-1, but the cursor should be on the top line and the rest of the lines should have the ~ blank line delimiter. Press i to move out of Command mode and into Insert mode, and you’re ready to enter text.

  2. Enter some lines of text. Make some lines too short (press Return before the line gets to the right margin). Make others too long; watch how vi wraps long lines. If you have another terminal window open with some text in it, or if you have an Aqua application open, you can also use your mouse to copy text from another window and paste it into the vi window. (Always make sure you’re in Insert mode before you do this, however, or you could irrevocably mess up your file.) To get a lot of text quickly, paste the same text more than once.

  3. Let’s practice moving around the file. To do this, we’ll need to leave Insert mode by pressing ESC once. Press it again and you’ll hear a beep, reminding you that you are already in Command mode. You can use your arrow keys to move around the file, but vi also lets you keep your fingers on the keyboard by using h, j, k, and l as the four motion keys (left, down, up, and right, respectively). Unless you have enabled “Option click to position cursor” in Terminal’s Preferences, vi will ignore your mouse if you try to use it to move the cursor. If you’ve entered a lot of text, you can experiment with various movement commands: H to jump to the first line on the screen, G to jump to the bottom of the file. You should also try the w and b commands, to move forward and backward by words. Also, 0 (zero) jumps to the beginning of the line, while $ jumps to the end.

    vi’s search or “where is” command, / pattern, can help you find a word quickly. It’s handy even on a short file, where it can be quicker to type / and a word than to use the cursor-moving commands. The search command is also a good example of the way that vi can move your cursor to the status line so you can enter more information. Let’s try it by typing /. You should see a display like Figure 4-2.

    vi display while searching

    Figure 4-2. vi display while searching

  4. Notice that the cursor has jumped to the bottom of the display (which has changed since you started vi) and is sitting next to a /. You can type a word or characters to search for, then press Return to do the search. After a search finishes, you can type n to repeat the search.

  5. If your text isn’t in paragraphs separated by blank lines, break some of it into paragraphs. Put your cursor at the place you want to break the text, and press i to move back into Insert mode, then press Return twice (once to break the line, another to make a blank line).

  6. Now justify one paragraph. Put the cursor at the beginning of the paragraph and type !}fmt. (vi’s status line won’t change until you press the } character.) Now the paragraph’s lines should flow and fit neatly between the margins.

  7. Text can be deleted by using x to delete the character that’s under the cursor, or the powerful d command: dd deletes lines, dw deletes individual words, d$ deletes to the end of the line, d0 deletes to the beginning of the line, and dG deletes to the end of the file (if you’re seeing a pattern and thinking that it’s d + motion specifier, you’re absolutely correct). To undo the deletion, press u. You can also paste the deleted text with the p command.

  8. The first step to copying text is to position your cursor. The copy command, or “yank,” works similar to the delete command. The yw command copies one word, yy yanks the line, y1 a single character, and y n w yanks n number words. Move the cursor to the line you want to copy and press yy. After repositioning your cursor to where you’d like the text copied, press p to paste the text.

  9. As with any text editor, it’s a good idea to save your work from vi every 5 or 10 minutes. That way, if something goes wrong on the computer or network, you’ll be able to recover the edited buffer since the last time you saved it. When launching vi again, use the -r option with a filename to recover the edited buffer where the filename is the name of the file you were editing.

    Try writing out your work with :w followed by Return. The bottom of the display will show the filename saved and the number of lines and characters in the file.

    This part confuses some vi beginners. If you want to save the file with the same name it had when you started, just press :w and Return. That’s all! You can also choose a different filename: type :w followed by the new filename. Press Return and it’s saved.

  10. Make one or two more small edits. Then, exit with :q. vi warns you that the file has not been saved. If you want to override the warning, type :q!. You can also use a shortcut: :wq writes out your changes and quits vi.

That’s it. There’s a lot more you can learn about. In Table 4-2, you’ll find a handy listing of some of the most common vi commands and their descriptions. O’Reilly has two very helpful books if you want to become a power user: Learning the vi Editor, by Linda Lamb and Arnold Robbins, and vi Editor Pocket Reference, by Arnold Robbins. Though focused on vi, they offer extensive information about vim as well, and will get you up to speed in no time.

Table 4-2. Common vi editing commands

Command

Meaning

/pattern

Search forward for specified pattern. Repeat search with n.

:q

Quit the edit session.

:q!

Quit, discarding any changes.

:w

Write (save) any changes out to the file.

:wq or ZZ

Write out any changes, then quit (shortcut).

a

Move into Append mode (like Insert mode, but you enter information after the cursor, not before).

b

Move backward one word.

w

Move forward one word.

d1G

Delete from the current point back to the beginning of the file.

dd

Delete the current line.

dG

Delete through end of file.

dw

Delete the following word.

ESC

Move into Command mode.

h

Move backward one character.

l

Move forward one character.

i

Move into Insert mode (ESC moves you back to Command mode).

j

Move down one line.

k

Move up one line.

O

Open up a line above the current line and move into Insert mode.

o

Open up a line below the current line and move into Insert mode.

P

Put (paste) deleted text before the cursor.

p

Put (paste) deleted text after the cursor.

X

Delete character to the left of the cursor.

x

Delete the character under the cursor.

yw

Yank (copy) from the cursor to the end of the current word. You can then paste it with p or P.

yy

Yank (copy) the current line. You can then paste it with p or P.

Get Learning Unix for Mac OS X Panther now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.