10. Editing Files

We can create files with touch and use cp to copy them. How do we edit text files and place information in them? This is the role of the UNIX text editor, vi. The O’Reilly book it comes highly recommended if you want to become a power user (you do). A second text editor, emacs is also available. It is powerful and extensible. Like vi it is a serious tool requiring serious learning, and like vi there is an O’Reilly book on it, too. You may use emacs instead of vi if you wish. Both of these are just tools for creating and editing text files, and both do a great job. You may create or modify any text file with either program. Ubuntu users can also use gedit or gvim, which have some nice advantages.

A Note for Ubuntu Users

Ubuntu by default installs the package vi-tiny. We want vi with all bells and whistles. To get this, make sure you are connected to the Internet, then type the following command in an terminal window.

unix> sudo apt-get install vim

You will be asked to enter your password, then it will install the full vi package. The sudo command tells Ubuntu you are behaving as a system administrator, so you must enter your password to proceed. It will ask you to confirm you wish to install, and then it will download the package from the repositories, install, and configure it for you. Ubuntu has lots of programs and packages that are freely available, and you use sudo apt-get install to obtain them.

10.1 Launching vi

To create a new file or open an existing file, type

unix> vi someFileName

at the UNIX command line. If the file someFileName exists, it will be opened; otherwise, it will be created. Now let us open the file bar we created with touch. You will see this:

~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
"bar" 0L 0C

DO NOT TYPE YET!

Read ahead so you avoid having a passel of confusing annoying things plaguing you. The tildes on the side indicate empty lines; they are just placeholders that are not a part of the actual file. It is fairly standard for the tildes to be blue. The OL OC "bar" indicates that file bar has no lines and no characters. If the file bar were not empty, its contents would be displayed, then blue tildes would fill any empty screen lines.

10.2 vi Modes

Before you hit any keys there is something important to know. The vi editor is a moded editor. It has four modes: command mode, visual mode, insert mode, and replace mode. You will sometimes see command mode referred to as normal mode.

Command mode provides mobility, search/replace, and copy/paste capabilities. Insert mode allows you to insert characters using the keyboard. Visual mode provides the ability to select text using the keyboard, and then change or copy it. Replace mode overwrites existing text with new text that you type in. When you first open a file with vi, you will be in command mode.

We will begin by learning how to get into insert mode; there are lots of ways to do this. Here are a six basic ones that are most often used.

keystroke Action
i insert characters before the cursor
I insert characters at the beginning of the line
a append characters after the cursor
A append characters at the end of the line
o open a new line below the cursor
O open a new line above the cursor

Here is an easy way to remember. What happens if you accidentally step on your cat’s tail? He says IAO!!!

image of an angry cat

There is one way to get out of insert mode. You do this by hitting the escape (ESC) key. Let’s now try this out. Go into your file bar and hit the i key to enter text. Type some text. Then hit ESC. To save your current effort type this anywhere:

 :w

This will write the file; a message will appear at the bottom of the window indicating this has happened. Do not panic; that message is not a part of the file that is saved. To quit, type

 :q

this will quit you out of the file. You can type

 :wq

to write and quit. The command :qw does not work for obvious reasons. You have just done a simple vi session. You can reopen the file bar by typing

unix> vi bar 

at the UNIX command line; the contents you last saved will be re-displayed. You should take a few minutes to try all of the ways of getting into insert mode. Change the file and save it. Quit and display it to the screen with cat and more.

At first, vi will seem clunky and awkward. However, as you ascend the learning curve, you will see that vi is blazingly fast and very efficient. One of its great strengths is the ability to search for and replace text. As your skill grows with it, you will see it is an amazing productivity tool. You might want to spend a little time at https://openvim.com, which is a great tool for learning vi.

10.3 A Reassuring Note

If you are in command mode and hit ESC, your computer will just beep at you. This is its way of letting you know you were already in command mode. Nothing additional happens. If you are unsure what mode you are in, hit ESC and you will be back in command mode, no matter what. You can hit ESC and relax.

The figure below will help you to see the relationship between insert and command modes. When you first start editing a file, you enter in in command mode. Typing i, a, o, I, A or O all put you into insert mode. You can also see in the diagram how to get out of insert mode by typing ESC.

|-------------------------------------------------------------
|          command mode                                       |
|     ---------------i, a, o, I, A, O to get in-----------    | 
|     |    insert mode:                                   |   |
|     |    insert characters                              |   |
|     |    paste in text with GUI                         |   |
|     -----------------------------------ESC to get out---    |
|          search, replace                                    |
|          copy with yy, paste with  p                        |
|          delete lines with dd                               |
|          all "colon commands" (commands that start with :)  |
|----------------------------------- -------------------------- 

Let’s go back in our file now and learn some more useful commands. We will look at command mode commands now.

Sometimes, line numbers will be helpful; these are especially useful when you program. To see them, you get into command mode and type the colon command :set number. Do this and watch them appear. Now type :set nonu or :set nonumber and watch them disappear. Line numbers are not a part of the file; however, they are a helpful convenience.

Here are some useful command mode mobility features. Experiment with them in a file.

Command Action
:lineNumber Go to indicated line number.
^ Go to the beginning of the current line.
$ Go to the end of the current line.
G Go to the end of the file.
gg Go to the beginning of the file; note that :1 also works.

These colon commands in this table will allow you to alter your editing environment. The last two are useful editing tricks that are sometimes quite convenient. Open a file and try them all.

Command Action
:set number display line numbers
:set nonu get rid of line numbers
:set autoindent This causes vi to autoindent.
:set noautoindent This causes vi to turn off autoindent.
r (then a character) replace character under cursor
~ change case
upper → lower
upper → lower

10.3 Cut and Paste

The vi editor has a cache of memory called the unstable buffer, which we nickname Mabel. Mabel provides a temporary place for holding things while we are editing and she is very helpful for doing quick copy-paste jobs.

This buffer is unstable because it loses its contents every time new text is placed in it. Do not use it to store things for a long time; instead write those things to files and retrieve them later. You will learn several ways to do this.

We show here a table with some cut, copy, and paste commands you will find helpful.

yy Yank line to Mabel
dd Delete line starting at the cursor; this cuts to Mabel
dw Delete word; this cuts to Mabel
cw Delete word, then enter insert mode(change word) The changed word is cut to Mabel.
p Paste Mabel’s contents at the cursor.
P Paste Mabel’s contents before the cursor.
D Cut line at cursor; this cuts the stricken text to Mabel
C Cut line at cursor and enter insert mode; this cuts the stricken text to Mabel

All of these commands can be preceded by a number, and they will happen that number of times. For example typing 10yy in command mode will yank ten lines, starting at the cursor, to Mabel. Since so many of these commands place new text in Mabel, you should know that if you copy or cut to Mabel and intend to use the text, paste it right away. You should open a file and experiment with these. Spend some time fooling around with this mechanism; you will make some delightful discoveries, as well as dolorous ones.

10.4 Using External Files

You can select a range of line numbers before each of these commands, or select in visual mode (next section) and use these commands.

:w fileName Write a copy of the entire file to fileName
:w! fileName Write selection to existing file fileName, and clobber it.
:w >> fileName Append selection to file fileName.
:r fileName Read in file fileName starting at the cursor

For example

    :20,25 w foo.txt

will write lines 20-25 to the file foo.txt. If you want to write the entire file, omit the line numbers and that will happen. If you want to write from line 20 to the end of the file, the usage is as follows.

    :20,$ w foo.txt

Note the use of $ to mean “end of file.” When you learn about visual mode (just ahead), you can use these command to act on things you select in visual mode as well.

Housekeeping Tip

If you use this facility, adopt a naming convention for these files you create on a short-term basis. When you are done editing, get rid of them or they become a choking kudzu and a source of confusion in your file system. Use names such as buf, buf1, etc as a signal to yourself that these files quickly outlive their usefulness and can be chucked.

Search and Replace

Finally we shall look at search capabilities. These all belong to command mode. Enter

 /someString

in command mode and vi will seek out the first instance of that string in the file or tell you it is not found. Type an n to find the next instance. Type N to reverse direction. You can enter

 ?someString

to search for someString backwards from the cursor. Type n to find the previous instance, and N to reverse direction. Your machine may be configured to highlight every instance of the string you searched for. If you find this feature annoying, you can deactivate it with

:set nohlsearch

Now let us look at search and replace. This is done by a colon command having this form.

:s/old/new/(g|c|i)

The s means substitute; this substitutes old for new. The three flags at the end specify how the substitution should work By default, substitutions are confined to the cursor line, but you can control the scope of a substitution in these two ways.

Bound Scope
a,b s/old/new/(g|c|i) Perform the substitution on lines a through b, inclusive.
a, $ Perform the substitution on line a until the bottom of the file.

Here is how the flags work. At the end you can append any of g, c, or i. Here is a decoder ring.

c Check after each substitution to see if you want to replace.
g Replaces all instances on each line. By default, only the first one is replaced.
i Replace old case-insensitive.

You will also learn how to control the scope of substitutions in visual mode below. That method is extremely nice and quite simple to learn.