Chapter 4. Creating and Editing Files

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.

Note

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.

Creating a File

Problem

You need to create a text file.

Solution

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

Note

See recipe 4-2 to learn how to move your cursor around within a file.

How It Works

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

vi

Starts editing session in memory.

vi <file>

Starts session and opens the specified file.

vi <file>*

Opens first file that matches the wildcard pattern. Use :n to navigate to the next matched file.

view <file>

Opens file in read-only mode.

vi -R <file>

Opens file in read-only mode.

vi -r <file>

Recovers file and recent edits after abnormal abort from editing session (like a system crash).

vi +n <file>

Opens file at specified line number n.

vi + <file>

Opens file at the last line.

vi +/<pattern> <file>

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

i

Insert text in front of the cursor.

a

Insert text after the cursor.

I

Insert text at the beginning of the line.

A

Insert text at the end of the line.

o

Insert text below the current line.

O

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.

Table 4.3. Useful vi Exit Commands

Exit Command

Action

:wq

Save and exit.

ZZ

Save and exit.

:x

Save and exit.

:w

Save the current edits without exiting.

:w!

Override file protections and save.

:q

Exit the file.

:q!

Exit without saving.

:n

Edit next file.

:e!

Return to previously saved version.

Maneuvering Within a File

Problem

You want to navigate efficiently within a text file while editing with vi.

Solution

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.

How It Works

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

j (or down arrow)

Move down a line.

k (or up arrow)

Move up a line.

h (or left arrow)

Move one character left.

l (or right arrow)

Move one character right.

Ctrl+f (or Page Down)

Scroll down one screen.

Ctrl+b (or Page Up)

Scroll up one screen.

1G

Go to first line in file.

G

Go to last line in file.

nG

Go to n line number.

H

Go to top of screen.

L

Go to bottom of screen.

w

Move one word forward.

b

Move one word backward.

0

Go to start of line.

$

Go to end of line.

Copying and Pasting

Problem

You want to copy and paste text from one section of the file to another.

Solution

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

How It Works

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

yy

Yank (copy) the current line.

nyy

Yank (copy) n number of lines.

p

Put yanked line(s) below the cursor.

P

Put yanked line(s) above the cursor.

x

Delete the character that the cursor is on.

X

Delete the character to the left of the cursor.

dw

Delete the word the cursor is currently on.

dd

Delete current line of text.

ndd

Delete n lines of text

D

Delete to the end of the current line.

Manipulating Text

Problem

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.

Solution

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.

How It Works

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

r

Replace the character that the curser is on with the next character you type.

˜

Change the case of a character.

cc

Delete the current line and insert text.

C

Delete to the end of the line and insert text.

c$

Delete to the end of the line and insert text.

cw

Delete to the end of the word and insert text.

R

Type over the characters in the current line.

s

Delete the current character and insert text.

S

Delete the current line and insert text.

Searching for and Replacing Text

Problem

You want to search for all occurrences of a string and replace it with another string.

Solution

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.

How It Works

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

/<pattern>

Search forward for a string.

?<pattern>

Search backward for a string.

n

Repeat the search forward.

N

Repeat the search backward.

f<character>

Search forward for a character in the current line.

F<character>

Search backward for a character in the current line.

Inserting One File into Another

Problem

While within vi, you want to copy in another file that exists in the current working directory.

Solution

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

How It Works

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

Joining Lines

Problem

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.

Solution

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;

How It Works

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;

Running Operating System Commands

Problem

While editing text within vi, you want to run an operating system command.

Solution

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

How It Works

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

Repeating a Command

Problem

You find yourself typing commands over and over again. You wonder whether there is a way to repeat the previously entered command.

Solution

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.

How It Works

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).

Undoing a Command

Problem

You want to undo the last command you typed.

Solution

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.

How It Works

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.

Note

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.

Displaying Line Numbers

Problem

You want to display line numbers in your text file.

Solution

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

How It Works

Sometimes when you're dealing with files, it's nice to see a line number to assist with debugging. Use the set number and set nonumber commands to toggle the number display.

Tip

Press Ctrl+G (the Ctrl and G keys pressed simultaneously) to display the current line number.

Automatically Configuring Settings

Problem

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.

Solution

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.

How It Works

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

Tip

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).

Creating Shortcuts for Commands

Problem

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.

Solution

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.

How It Works

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

Setting the Default Editor

Problem

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.

Solution

Use the export command to set the default editor. The following example sets the default editor to the vi utility:

$ export EDITOR=vi

How It Works

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.

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

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