Unix Unit 2 Part 1
Unix Unit 2 Part 1
1211
complet ion and multiple
• Learn t~ use the two powerfu l features available in via--wo rd
undoing .
7 .1 vi BASICS
filename s01Detext:
For a quick tour ofvi, let's add some text to a file. Invoke vi with the
Th e Vi Edita vi sometex t
In all probabili ty, the file doesn't exist, and vi presents you a full screen
with the filename shown at
(
NoIImatter
h
at ~or
d
k you o w1'th the UNIX
h e to edit
system, you'Jl eventual
some of
fil
B
ly .write some C progr,._
the system I es at times. For all this You~,
. J
I the bonom with the qualifier , [New File]. The cursor is position ed at
lines ofthe screen (except the last) show a -. You can't take your cursor there
the top and alJ remaini ng
yet; they arc nonexist ent
text. This line is also used
lines. The last line is reserved for comman ds that you can enter to act on
1
w .
) cnpts You may av
..
• •and UNIX provides a very versatile one-vf . 1B11 oy created
M this cd''
she
I to peransc:d1tor,
oruse: II UNIX lltf~
by the system to display messages .
earnBSD system. The program is now standard on d' a h systems.
t d' dram1 oolenaar imp 1 is the mode where you
the
. 'll
the fe•ru. You are now in the Comman d Mode, one ofthe three modes used by vi. This
d " II , d ..
..• ••available • (..• ,·mproved). In this text we 1scuss t e v e ttor an a so note
•in• iLinux.
can pass comman ds to act on text, using most of the keys of the keyboard
. Pressing a key doesn't
the next line, or deleting a
show it on screen but may perform a function like moving the cursor to
1.w, any «lito, ,t • .,,. nombe, of intemal command, 10 navigate to any point
in a "'' fil line. You can't use the Comman d Mode to enter or replace text.
«lit thmxt tb;.,_ h ,l,oallow, you to copy •nd move text within a file and also from
.,
a terminal . To enter text,
For text editing, vi uses 24 of the 25 lines that arc normally available in
,notbe,. ri offe,, eryptk, and ,om,tim« tnn<monk, intemal comman d, fo, editing Wotl0
It~
arc in this mode ready to
• ma,1 you must switch to the Input Mode. First press the key marked i, and you
<ompleo, w, ofth, keybo,ro wh,,, P"tti<ally evc,y key ha, a function . You don't need input text. Subsequ ent key depressio ns will then show up on the screen as
text input. Stan insening
,, upoow;
righ, IT of thisknowl,dg,
• wodcing book. i, all th,i i, <equin,d initially. The advance d fcatu,e, of,,;
taken in Part a few lines of text, each line followed by [Enter}, as shown in Fig. 7.1.
r of the last line. This is
WHATYouwlLLLEARJv After text entry is complete , the cursor is positione d on the last characte
is the current cursor
known as the current line and the characte r where the cursor is stationed
• Th< th.,, mod,, ;. whi,h ,, op,,a1c, fo, sharing the woddoad . key to wipe it out. If a
position . If you ~cc somethin g that shouldn 't be there, use the backspac e
• Use a r~eat factor to repeat a command multiple times. word has been m1sspelled, use [Ctrl-w} to erase the entire word.
• Use: the: Input Mode to insc:n and replace text. you'll hear a beep; a beep
• Use: the ex Mode to save: your Work. ~ow ~re~s the [Esc] key to tevert to Comman d Mode. Press it again and
m vi _md1cates that a key has been pressed unnecess arily.
• Use the Command Mode to n,...l'orm . .
Unit fo navigation.
• Use: the: word as a navigationr•u
• Delete, Yank (copy) a d . r _movement along a line.
• Undo the last ed'ti n move . text using 0'Perator.r. This is the vi editor{E nter}
J ng action and rep th I It is slow in getting started but is quite powerful [Enter}
• Search for a Pattern and repeat the eat h e ast command . It operates in three rnodes[Enter}
• Use the Cle M d scare .
All the features of ex are also availabl e[Enterj
r.
o e to perform String substitutio You can even escape to the UNIX shell{En ter}
O
T Pics OF SP£c1,u_b r,.w, __ n. I
It maintain s 26 buffers for storing chunks of text
Master the techniqu f ~ - - ~
, CO Us1
OllJe action and ("') ng a three-fun ·
111 repeat
, "ftdCtio~
the SC.arch ... sequence to (i) search for a pattern (ii) take
, action.
Fig. i'.l Inserting Some Text
i_,_~} UNIX: Concepts and Applications
The file sometext doesn't exist yet. Actually, the text that you entered hasn't bee·n saved on disk but
'
• in some temporary storage called a buffer.
extSls
• h to.thc
To save the entered text, you mu st switc
ex Mode (also known as Last Line Mode). Invoke the ex Mode from the Command Mode by entenng
a : (colon), which shows up in the last line. Enter an x and press [Enter}:
:x[Enter)
"sometext" 6 lines, 232 characters
$ _ Quits editor-back to shell prompt
The file is saved on disk and vi returns the shell prompt. To modify this file, you'll have to invoke
vi sometext again. But before moving ahead, let's summarize the modes used by vf:
• Command Mode-The default mode of the editor where every key pressed is interpreted as
a command to run on text. You'll have to be in this mode to copy and delete text. Unnecessary
pressing of [Esc] in this mode sounds a beep but also confirms that you are in this mode. .
• lnput_~odc-Every key pressed after switching to this mode actually shows up as text. This
mode is invoked by pressing one of the keys shown in Table 7.1.
• ex Mode (or Last Line Mode)-The mode used to handle files (Jike saving) and perform
•
substitution. p ressing a : in tile Command Mode invokes this mode. You then en ter an ex
1
I
Mod~ command followed by [Enter}. After the command is run, ~ou are back to the defau t
Command Mode.
Much of the chapter deals with Command Mode commands where most of the action is, Some of
these commands also have ex Mode equivalents which are sometimes easier to use. But a~l th_ree
:odes also have their own exclusive features and an editing session in vi involves constant switching
etwecn modes as depicted in Fig. 7.2.
• vi reads the TERM variable to determine the file that contains the terminal's characteriScics.Ai
discussed later (10.3), vi actually reads a system file to know the control sequences that app_ly
to the terminal name assigned to TERM. You should always check TERM whenever vi behavmn
an awkward manner.
Note: Only the keys g, K, q, v, V and z have no function in the standard vi implement.ation. Somed
them are defined, however, in vim.
Tip: Before you start using the Input Mode commands, enter this ex Mode command:
:set showmode[Enter}
Enter a : (the ex Mode prompt) and you'll see it appear in the last line. Follow it with the two words;;Ed
press {Enter]. showmode sets one of the parameters of the vi environment Messages like INSERT M '
REPLACE MODE or CHANGE MODE, etc. will now appear in the last line when you run an Input Mode
command. We'U learn later to make the setting permanent by placing it in $HOME/. exrc.
the vi
a. a 1ink of ex[Esc]
Fig. 7.3 Text Insertion with i Fig. 7.'I Text Appending with a
There are other methods of inputting text. To append text to the right of the cursor position, use
followed by the text you wish to key in (Fig. 7.4). After you have finished editing, press {Esc]. With
t and a, you can append several lines of text in this way.
These two commands arc suitable: for converting code to comment lines in a C program (Fig. 7.5).
A comment line in C is of the: form /* comment */. Use I on an existing line that you now wish to
convert to a comment, and then enter the symbols/*. After pressing {Esc}, use A to append*/ at the
end of the line and press [Esc] again.A document author often needs to use A to continue text entry
from the point work was suspended -adding a sentence to a paragraph, for instance.
t I/* [Esc]
• A *l[E_sc}
Tip: C language programmers sometimes precede a block of comment lines with a pattern likethi;'
/**********************************************************************
It seems that there are 70 asterisks here, and to draw them you should use a repeat factor. Mer YoU
have entered / in the Input Mode, press [Escj, and then enter 70a*[Escj, You'll see 70 asterisks appended
to the/.
r No {Esc] required
rT
9lis is the vi full-screen editor
v1 1s
•
I link of ex
sone[EscJ t
vi is one of the Inks of the ex program
Rmodes[fac]
Fig. 7.8 Replacing Text with s Fig. 7.9 Replacing Text with R
followed by the character that replaces the one under the cursor (Fig. 7.7). You can replace a single
character only in this way. vi momentarily switches from Command Mode to Input Mode when r
is pressed. It returns to Command Mode as soon as the new character is entered. There's no need
to press [Esc] when using r and the replacement character, since vi expects a single character
anyway.
When you want to replace the letter d with !Of in a printf statement in C, you need to replace one
character with three. In that case, press
Replaces one character with many
s
vf deletes the character under the cursor and switches to Input Mode. It may also show a $ at that
location to indicate that replacement will not affect text on its right. Now enter lOf and press [Esc}.
To replace multiple characters, use a repeat factor. 3s replaces three characters with new text. Use
of sis shown in Fig. 7.8.
Rand S act in a similar manner compared to their lowercase ones except that they act on a larger
group of characters:
R Replaces all tex_t on the right of the cursor position.
S Replaces t!ie entire line irrespective of cursor position. (Existing line disappears)
Try using the repeat factor with Rand Sand see whether you can take advantage ofthis feature. Use
ofR is showrl in Fig. 7.9.
You have now been able to enter the Input Mode in ten ways. The functions of these ten keys are
summarized in Table 7.1.
Caution: You must press /Esc/ to switch to Command Mode after you have keyed in text. Repeated
pressing of /Esc/ won't make any difference to vi except that it has a built-in capability to indicate with
a beep If a key has been pressed unnecessarily. Try this by pressing [Esc} several times. You are now in
the Command Mode.
Tip: The best way to save and quit the editor is to use ZZ, a Command Mode command, instead of
:x or :wq.
to return you to the prompt irrespective ofthe status ofthe buffer-no questions asked. vi suggests
appending a I to an ex Mode command every time it feels that you could be doing something that
is potentially unsafe.
Note: In general, any ex Mode command used with a ! signifies an abort of some type. It can be used
to SWitch to another file without saving the current one, or reload the last saved version of a file. You can
e1.en use it to overwrite a separate file.
saves lines 10 through ~0 to the file n2words. pl. You can save a single line as well:
: Sw n2words. p1 Writes 5th line to anotherfile
Co UNIX: Concepts and
Applications
. . d S T he do t
T he re are tw o sym •th ha -t
bols used w1 w~ t have special significance h e do t an • . binaoon•
th e cu rr en t line w hi \ si
le $ represents e tl in eo ft he file. You ca n us e th em ng ly or in coJll
as
· (where cursor tJ positioned)
.
: .w te m pf H e Saves current 1m e
:$w te m pf ile Saves lastline .
: . ,$-.. te m pf ne Saves current line th h end
roug
If tempfl 1e exists an d . . . .
is w nt ab le by you, •
vi issues yet an ot he r w ar ni ng .
"tempfi1e" FH e ex
is ts - use •w! tem f"1 " to ov er
p 1 e 'fl rit e
T he message is de ar : .
vi 1s te \h.ng yo u to ffi h , o th e w ri te tetnP file,
:w co m m ar .d to ov erd
L.
As m en tio ne d be fo su ix t e • t u' ll""
re , th e ! is th e un iv
er sa l ov em·d·mg oper at or 1•n th e ex M o e an d yo
us in g it of te n.
7.4 NAVIGATION
is the mode you come to when you
We'll now consi der the funct ions of the Com mand Mode. This
command doesn't show up on
have finished enter ing or chan ging your text. A Comm and Mode
Don't forget to avoid the cursor
screen but simply perfo rms a funct ion. We begin with navigation.
control keys for navig ation as advised in Section 7.13.
I takes you
'--/
13h
Fig. 7.10 Relative Navi
gation wi th h, j, k an d 1
Th r
e repeat 1a ~tor ca n be used as a co
the curso mmand prefix wi th all r us
m ands. Th ' 4k moves•
r 4 lines up an d 20h tak these 1o u~ co ~ .th th e four keys_ JS
sh ow n in Fi g. 7.10. No es it 20 characters to th
e left. Nav1gat.1on ~ 1
these keys.
te th at this motion is rel
ative; you ca n't move to r umberwith
a specific in e n
Tip •
Th ·Tc
• 0 remember th e keys
th
e left-most key, h, move at move the cursor left or right, observe these fou k o n ~
s th e cursor to th e left, an r
d the right-most key, 1 (el eys 1. ri hl
), moves ~
7 •4
.2 W or d Navi gation (b, e and w)
Movin b .
g Yon e character is no \
u nderstands a word as t always enough· you'l
ter a Iong a lin
a navigation un it which l often need to move fas e. vi
presdsed. I~ yo ur curso ~an be defined in two wa th key
r is a nu m be r of word ys, de pe nd in g on e the
Wor -n av s away from your desir
ig ati•on co mm an ds to go ed position, you ca n us
there directly. Th er e are • e
three basic comm•an ds:
b Moves ba ck to be gi nn in
g of word
e Moves forward to en d
ofwo rd
w Moves forward to be gi
nn in g of word
A re pe at factor speeds
up cursor movement alo
:io~~s back,. while 3w ng a line. For example,
takes th e cursor three Sb takes the cursor five
p nu m en c characters wo rds ~orward. A wor~ he
an d th e (underscore). re is simply a s~ in g of
"'Ords; th e hy ph en by Bash 1s one word; so 1s sh
_p rofi 1e. tcp -f p 1s three
definition becomes a wo
rd too.
Th e keys B, Ean d Wpe
rform functions simila
pu n~ tu ati on is skipped r to those of th eit lowerc
deta ds . . Th e word definition als ase counterparts except th
o gets changed here, bu at
• • t we'll ignore these mino
r
The vi Editor
Fl
7 .4.3 Moving to Line Extremes {O, I and $)
Mo~ipg to the beginning or end of a line is a common requirement. This is handled by the keys O,
I and $. To move to the first char~cter of a line, use
0 (zero) or I 30 I moves cursor to column 30
The I takes a repeat factor and using that, you can position the cursor on a certain column. To
position the cursor on column 30, use 30 I-
We used$ as the line address in the ex Mode to represent the last line of the file. The same symbol
in the Command Mode represents the end ofline. To move to the end of the current line, use
$ Moves to md ofline
The use of these two commands along with those that use units of words (b, e and w) is shown
in Fig. 7.11.
Note: When you use the keys b, e and w, remember that a word is simply a string of alphanumeric
characters and the _ (underscore).
Oor I
e 4e 4w
s three commands
Note: The exMode offers equivalent commands for moving between lines. The previou
can be replaced with : 40, : 1 and : $, respectively (along with /Enterfl
.
t
This is the vi fullascreen editor· from UCB
t
This is the vi lillscreen editor from UCB
4x
A Windows Notepad user would be surprised to note that when the cursor is at the end of a line, x
doesn't pull up the following line but works instead on text on the left ofthe cursor. Deletion oftext
from the left is otherwise handled by the Xcommand. Keep it pressed, and you'll sec that you have
erased all text to the beginning of the line.
Entire lines are removed with the dd "command" (rather a doubled operator). Move the cursor to
any line and then press
6dd deletes the current line and five lines below. Fig. 7.13 illustrates the use of dd both with and
without a repeat factor. There are other forms of deletion available in vi and you'll know them all
after you have understood the d operator well (20.1.l).
• dd
a is superior toed, and friendlier too
It is due to William Joy
It is slow in get tin g sta rte d but
i
is qu ite powerful
2dd
f: is slow in get tin g sta rte d but is
qu ite powerful
Fig. 7.13 Deleting Lines with dd
For instance, to correct sdt io. h to std
io.h, you'll have to transpose the
delete thed and put it after the t. Move characters d and t,t
your cursor to the din sdt i o. han d use
these two commao
x sdtio.h becomes stio .h- -cu rso r on t
P d put on rig ht- sti o. h becomes std io.
h
Since we worked on parts oflines, asso
ciate the word "right" with p and "le
on the left of the cursor. ft" with P. Pplaces tat
.
To put entire (deleted) lines at a differen
t location, you'll need to use the sam
that we have to think in terms of "below e commaods, except
" and "above" the current line. p pla
current line and Pplaces text above. ces text below tbe
J removes the newline characte r between the two lines to pull up the line below it.Joinin g, however
,
is restricte d to the maximu m line size that your vi editor can support. It could be below 2000 (as in
Solaris) or unlimite d (in Linux).
To solve the problem posed at the end of the previous section, if you place a line below the current
line with p, you can use J to join the two lines.
reverses all changes made to the cuccent line, i.e., all modifications that have been made since the
cursor was moved to this li~e.
Caution: Make sure the cursor h~s.not been moved to another line before invoking U, in which case it
won't work. "-'
i.iii i:'~ Cindolng and Ids you undo "'anct redo • l e editing
here; repeated use d this key progresslYely ·unc1oes your previous actions.
t- =":""'..!".~"'""'"""'.""":::--... t•~ =i
1badel nd mark when you keep II P'essed. In whldl case me /Ctrl-1/ to redo~
iiriilalns wlthDII can be campletely nN'elSed wab-10/0rl-l/.The undoing 11m1
sset undoltv els~ wheren ~•to tOOObydefault. J