If you want to survive in a Linux environment, then you must be adept with at least one command-line text editor. DBAs use text editors on a daily basis to manipulate database initialization files, create scripts to automate tasks, modify operating system scheduler jobs, and so on. In a Linux shop, you won't be able to do a good job as a database administrator unless you're proficient with a text editor.
Dozens of text editors are available. To that end, there have been entire books written on text editors available in Linux/Unix environments. The three most common command-line text editors in use are vi
, Vim
, and emacs
. This chapter focuses on the vi
text editor (pronounced "vee-eye" or sometimes "vie"). We chose to concentrate on this editor for the following reasons:
The vi
editor is universally available on all Linux/Unix systems.
DBAs tend to use vi
more than any other editor.
You can't consider yourself a true Linux geek unless you know vi
.
The goal of this chapter is to give you enough information to efficiently use the vi
editor. We don't cover every facet of vi
; rather, we focus on the features that you'll find yourself using most often to perform daily editing tasks. When you first use vi
, you may soon wonder why anybody would use such a confusing text-editing tool. To neophytes, many aspects of vi
will initially seem counterintuitive. Not to worry, with some explanation, examples, and hands-on practice, you'll learn how to use this editing tool to efficiently create and manipulate text files. This chapter contains more than enough material to get you started with vi
. The problems described are the most commonly encountered editing tasks.
If you are new to vi
, we strongly encourage you to not just read the solutions in this chapter but actually to start up a vi
session and practice entering the commands shown in the examples. It's like riding a bicycle, and you can't learn how to ride until you physically get on the bike and attempt to go forward. It's the same with vi
. You can't just read about how to use this tool; you have to type commands before the learning takes place.
All the solutions and examples in this chapter also work nearly identically with the Vim
editor. The vi
-improved (Vim
) editor provides many enhancements to vi
.
To create a file named foo.txt
, run the vi
utility from the command line, as shown here:
$ vi foo.txt
You should now see a blank screen with several tilde (˜
) graphemes displayed in the far-left column of the screen. Within a file being edited by vi
, the ˜
character indicates a line that has no text on it. Depending on your version of vi
, you may see the name of your file in the bottom-left corner:
"foo.txt" [New file]
To enter text, first type i
. You can now enter text into the file. To save your changes and exit from vi
, first press the Esc key, and then type :wq
for write and quit:
:wq
You should now be back at the operating system command prompt. You can verify that the new file has been created with the ls
command:
$ ls foo.txt foo.txt
See recipe 4-2 to learn how to move your cursor around within a file.
The most common way to start vi
is by providing it with a file name to operate on:
$ vi <filename>
Several options are available when first invoking vi
. Table 4-1 lists some of the more commonly used command-line choices.
Once you've started a vi
session, it's critical to understand that there are two distinct operating modes:
Command mode
Insert mode
Table 4.1. Some Helpful vi
Command-Line Startup Options
Option | Action |
---|---|
| Starts editing session in memory. |
| Starts session and opens the specified file. |
| Opens first file that matches the wildcard pattern. Use |
| Opens file in read-only mode. |
| Opens file in read-only mode. |
| Recovers file and recent edits after abnormal abort from editing session (like a system crash). |
| Opens file at specified line number |
| Opens file at the last line. |
| Opens file at first occurrence of specified string pattern. |
The vi
editor behaves very differently dependent on its mode. When you first enter vi
, you are by default in command mode. In this mode, you can enter commands that control the behavior of vi
. For example, you can issue commands to do the following:
Save a file.
Enter insert mode.
Exit vi
.
When in command mode, everything you enter is interpreted as a command by vi
. You cannot enter text into your file while in command mode. You must place vi
in insert mode before you can start entering text. Table 4-2 lists several methods of placing vi
in insert mode. Keep in mind that these commands are case sensitive. For example, the A command comprises pressing the Shift and A keys simultaneously.
Table 4.2. Common Techniques to Enter vi
Insert Mode
Enter Insert Command | Action |
---|---|
| Insert text in front of the cursor. |
| Insert text after the cursor. |
| Insert text at the beginning of the line. |
| Insert text at the end of the line. |
| Insert text below the current line. |
| Insert text above the current line. |
The easiest way to change from command mode to insert mode is to press i on the keyboard. This allows you to begin entering text at the place on the screen where your cursor is currently located. When in vi
insert mode, you can perform two activities:
Enter text.
Exit from insert mode.
While in insert mode, you should see text at the bottom of your screen indicating that you are in the correct mode (this may vary depending on your version of vi
):
-- INSERT --
You can now enter any desired text into the file. Everything you type will be interpreted by vi
as text that you want entered into the file.
To exit from insert mode (and back to command mode), press the Esc key. There's nothing wrong with pressing Esc multiple times (other than wasting energy). If you are already in command mode and press the Esc key, you may hear a bell or a beep.
You can exit from vi
(back to the operating system prompt) once you are in command mode. To save the file and exit, type:wq
(write quit):
:wq
If you've made changes to a file and want to exit without saving, then type :q!
, as shown here:
:q!
Table 4-3 details some of the more common exit methods. Keep in mind that you have to be in command mode before you can type a vi
exit command. If you don't know what mode you're in, press the Esc key to ensure you're in command mode. Notice that these commands are case sensitive. For example, the ZZ
command is executed by simultaneously pressing the Shift key and the Z key twice.
The most intuitive way to move around is by using the up/down/right/left arrows. These keys will work whether you are in command mode or insert mode. However, you may encounter some keyboards on which the up/down/left/right arrows don't work. In those cases, you'll have to use the J, K, H, and L keys to move you down, up, left, and right respectively. You must be in command mode to navigate with these keys. If you're in insert mode and try to use these keys, you'll get a bunch of jjj kkkkk hhh llll
letters on your screen.
Using these keys may seem cumbersome at first. However, you'll notice after some time that you can navigate quickly using these keys because you don't have to move your fingers from their natural typing positions.
You can use a myriad of commands for moving around in a text file. Some of these commands may seem confusing. However, with a little practice, the navigational commands will soon become second nature to you. Keep in mind that the vi
editor was designed to allow you to perform most tasks without having to move your hands from the standard keyboard position.
Table 4-4 contains commonly used commands to navigate within vi
. Remember that you must be in command mode for these keystrokes to work. Notice that these commands are case sensitive. For example, to navigate to the top of the page, use the 1G command, which is comprised of first pressing the 1 key and then simultaneously pressing the Shift and G keys.
Table 4.4. Common Navigation Commands
Command | Action |
---|---|
| Move down a line. |
| Move up a line. |
| Move one character left. |
| Move one character right. |
| Scroll down one screen. |
| Scroll up one screen. |
| Go to first line in file. |
| Go to last line in file. |
| Go to |
| Go to top of screen. |
| Go to bottom of screen. |
| Move one word forward. |
| Move one word backward. |
| Go to start of line. |
| Go to end of line. |
Use the yy
command to yank (copy) lines of text. Use the p
command to put (paste) lines of text elsewhere in the file. As with all vi
commands, ensure that you are in command mode (press the Esc key) before using a command. The following example copies five lines of text from the current line that the cursor is on and four lines below the current line (for a total of five lines):
5yy
You should see an informational line at the bottom of the screen indicating success (or not) of placing the copied lines in the copy buffer:
5 lines yanked
To paste the lines that have been copied, use the p
command. To put the lines beneath the current line your cursor is on, ensure you are in command mode, and issue the p
command:
p
You should see an information line at the bottom that indicates the lines were pasted below the line your cursor is on:
5 more lines
Copying and pasting are two of the most common tasks when editing a file. Sometimes you may want to cut and paste. This task is similar to the copying and pasting example in the "Solution" section of this recipe. Instead of using the yy
command, use the dd
(delete) command. For example, to cut five lines of text (inclusive with the line your cursor is currently on), issue the dd
command:
5dd
You should see a message at the bottom of the screen indicating that the lines have been cut (deleted):
5 fewer lines
Those lines are now in the buffer and can be pasted anywhere in the file. Navigate to the line you want to place the previously cut lines after, and press the p
command:
p
You should see an informational line at the bottom that indicates the lines were pasted after the line your cursor is on:
5 more lines
There are many commands for cutting and pasting text. Table 4-5 describes the copying, cutting, and pasting commands. Notice that these commands are case sensitive. For example, use the X
command to delete one character to the left of the cursor, which means pressing the Shift and X keys simultaneously.
Table 4.5. Common Options for Copying, Deleting, and Pasting Text
Option | Action |
---|---|
| Yank (copy) the current line. |
| Yank (copy) |
| Put yanked line(s) below the cursor. |
| Put yanked line(s) above the cursor. |
| Delete the character that the cursor is on. |
| Delete the character to the left of the cursor. |
| Delete the word the cursor is currently on. |
| Delete current line of text. |
| Delete |
| Delete to the end of the current line. |
You wonder whether there are some commands to modify the current text you're working on, such as changing a character from lowercase to uppercase.
Use the ˜
(tilde) command to change the case of a character. For example, say you have a string in a file with the text of oracle
and you want to change it to Oracle
. Place your cursor over the o
character. Hit the Esc key to ensure that you're in command mode. Type the ˜
character (which requires you to press the Shift key and the ˜
key at the same time). You should see the case of the character change from o
to O
.
Several commands are available for manipulating text. Table 4-6 lists common options used to change text. Notice that these commands are case sensitive. For example, the C
command is executed by pressing the Shift and C keys simultaneously.
Table 4.6. Common Options for Changing Text
Option | Action |
---|---|
| Replace the character that the curser is on with the next character you type. |
| Change the case of a character. |
| Delete the current line and insert text. |
| Delete to the end of the line and insert text. |
| Delete to the end of the line and insert text. |
| Delete to the end of the word and insert text. |
| Type over the characters in the current line. |
| Delete the current character and insert text. |
| Delete the current line and insert text. |
If you want to search only for a string, then use the / command. The following example searches for the string ora01
in the file:
/ora01
To search for the next occurrence of the string, use the n
(next) command:
n
To search backward for a previous occurrence of the string, use the N
command:
N
If you want to search for text and replace it, then use the s
option to search for text, and replace it with an alternate string. The following example searches for the string ora01
and replaces it with ora02
everywhere in the file:
:%s/ora001/ora02/g
All occurrences of ora01
should now be displayed as ora02
.
Searching for strings is one of the most common tasks you'll perform while editing database initialization files. Table 4-7 lists some of the more common options for searching for text.
Table 4.7. Common Options for Text Searching
Option | Action |
---|---|
| Search forward for a string. |
| Search backward for a string. |
| Repeat the search forward. |
| Repeat the search backward. |
| Search forward for a character in the current line. |
| Search backward for a character in the current line. |
While within vi
, you want to copy in another file that exists in the current working directory.
Use the :r
command to read in a file. This has the effect of copying in a file and pasting it starting at the current cursor location. This next example reads a file named tnsnames.ora
into the current file:
:r tnsnames.ora
The previous example assumes that the tnsnames.ora
file is in your current working directory. If the file you want to bring in is not in your current working directory, then you'll need to specify a path name. This example reads in a file from a directory that is not the current working directory:
:r /oracle/product/11.1/network/admin/tnsnames.ora
If you have an operating system variable that contains a path, you can use that directly. This example copies in a file contained in a path specified by a variable:
:r $TNS_ADMIN/tnsnames.ora
You'll often find the need to insert the content of a file into the current file you're editing. Doing so is a quick and easy way to add text to your current file that you know is stored correctly in a separate file.
You have a few other interesting ways to read in files. The next example copies in a file and places it at the beginning of the current file:
:0r tnsnames.ora
The following bit of code reads in the file at the end of the current file:
:$r tnsnames.ora
You have one line of text just after the current line you are editing. You want to join the text after the current line to the end of the current line.
First ensure you are in command mode by pressing the Esc key. Next place your cursor on the first line that you want to join with the line after it. Then type the J
(capital J) command to join the end of the current line to the start of the line after it.
An example will help illustrate this concept. Say you have these two sentences in a file:
select table_name from dba_tables;
If you want to join the first line to the second line, place your cursor anywhere on the first line, and type the following:
J
You should now see both lines joined together:
select table_name from dba_tables;
You'll use the J
command often to join two lines of code together in a text file. You can also join any number of consecutive lines. For example, say you have the following three lines in a file:
select username from dba_users;
You want the three lines to be joined together on one line. First place your cursor anywhere on the first line, and then while in command mode type the following:
3J
You should now see the three lines joined together, as shown here:
select username from dba_users;
First make sure you are in command mode by entering the Esc key. Use the :!
command to run operating system commands. For example, the following bit of code runs the operating system date
command without exiting vi
:
:!date
Here is the output for this example:
Sat Feb 10 14:22:45 MST 2008 ˜ Hit ENTER or type command to continue
Press the Enter or Return key to place you back into vi
command mode. To read the output of date
directly into the file you're editing, use this syntax:
:r !date
Running operating system commands from within vi
saves you the hassle of having to exit the utility, run the OS command, and then reenter the utility. DBAs commonly use this technique to perform tasks such as listing files in a directory, printing the date, or copying files.
The following example runs the ls
(list) command from within vi
to view files in the current working directory:
:!ls
Once the file of interest is identified, then you can read it in with the :r
syntax. This example reads the script1.sql
file into the file currently being edited:
:r script1.sql
If you want to temporarily place yourself at the shell prompt and run several operating system commands, then type your favorite shell with the :!
syntax. The following example enters the Bash shell:
:!bash
To return to vi
, use the exit
command to log out of the shell. At this point, you need to hit the Enter or Return key to return to vi
command mode:
Hit ENTER or type command to continue
You find yourself typing commands over and over again. You wonder whether there is a way to repeat the previously entered command.
Use the .
(period) command to repeat the previously entered command. For example, suppose you delete a large section of code but only want to delete ten lines at time. To achieve this, first ensure you're in command mode (by pressing the Esc key), and then enter the following:
10dd
To repeat the previous command, type a period:
.
You should see another ten lines deleted. This technique allows you to quickly repeat the previously run command.
You can use the .
command to repeat any previously typed command. You'll use the repeat command feature quite often. It will save you a great deal of time and typing. If you find yourself often retyping lengthy commands, consider creating a shortcut to the keystrokes (see recipe 4-13 for details).
To undo the last command or text typed, use the u
command. Make sure you are in command mode, and type u
, as shown here:
u
You should see the effects of the command that was typed in previously to the u
command being undone.
The u
command is handy for undoing the previous command. If you want to undo all commands entered on one line, use the U
command. The U
command operates only on the last line you changed. Your cursor must be on the last line you changed for this command to work.
If you want to undo changes since the last time you saved the file, type the following:
:e!
Sometimes the previous command is handy if you want to undo all edits to a file and start over. This is quicker than exiting the file with the :q!
(quit without saving) command and reopening the file.
The behavior of u
and U
may slightly vary depending on your version of vi
. For example, with vim
, you can use the u
command to undo several previous edits.
Use the set number
command. The following command will change the screen to display the line number on the left side of each row:
:set number
You should now see line numbers on the left side of the screen. The following is a snippet from the init.ora
file with the set number option enabled:
1 db_name=RMDB1 2 db_block_size=8192 3 compatible=10.2.0.1.0 4 pga_aggregate_target=200M 5 workarea_size_policy=AUTO 6 sga_max_size=400M 7 sga_target=400M 8 processes=200
You want to configure vi
to start up with certain settings. For example, you'd like to have vi
always start up in the mode of displaying line numbers.
If you want to customize vi
to automatically show line numbers, then create a file named .exrc
in your home directory, and place the desired settings within it. The following example creates a file named .exrc
in the home directory:
$ vi $HOME/.exrc
Enter the following text in the .exrc
file:
set number
From now on, every time you start vi
, the .exrc
file will be read, and the settings within it will be reflected in the files being edited.
Setting the line numbers to automatically appear is just one aspect that you can configure in the .exrc
file. To view all settable attributes in your environment, issue the following command within vi
:
:set all
Here is a very small snippet of the output:
--- Options --- ambiwidth=single joinspaces softtabstop=0 noautoindent keywordprg=man -s startofline noautoread nolazyredraw swapfile noautowrite lines=30 swapsync=fsync noautowriteall nolist switchbuf= background=light listchars=eol:$ tabstop=8
Notice that options that expect a value contain an =
sign in the output. To view the current setting of a feature, use set
and the option name. This example displays the term
setting:
:set term term=cygwin
To view which options are different from the defaults, use the set
command with no options:
:set
You can also put shortcuts for commands in your .exrc
file. Recipe 4-13 describes how to create command shortcuts (also referred to as command maps).
You find yourself using a certain command over and over again. You wonder whether there's a way to create a shortcut for the command.
Use the map
command to create a shortcut for a sequence of keystrokes. One set of keystrokes that is typed often is xp
. This command will transpose two characters (it performs a delete and then a put). This example creates a macro for the xp
command:
:map t xp
You can now use the t
command to perform the same function as the xp
command.
Mapping commands is a useful way of creating shortcuts for frequently used sequences of keystrokes. If you want mappings defined for each vi
session, then place the mappings in your .exrc
file (see recipe 4-12 for details).
To view all defined mappings, type :map
without any arguments:
:map
To disable a mapping, use the :unmap
command. The following example disables the t mapping:
:unmap t
You're editing the cron
table on a new database server. The default editor used for cron
is emacs
. You want to set your default editor to be vi
.
Use the export
command to set the default editor. The following example sets the default editor to the vi
utility:
$ export EDITOR=vi
Some utilities like cron
inspect the operating system EDITOR
variable to determine which editor to use. Some older systems may use the VISUAL
variable as well. The following lines can be placed in your HOME/.bashrc
startup file to ensure that the editor is automatically set when logging in:
export EDITOR=vi export VISUAL=$EDITOR
We recommend that you set both the EDITOR
and VISUAL
variables because some utilities (like SQL*Plus) will reference one or the other.