UNIX Fundamentals Workshop 59
______________________________________________________________________________
Chapter Three
Using the vi Editor
Why Use vi?
Modes of vi
Input and Delete
Cut and Paste
Undo
Search and Replace
Quit
Customizing
vilearn.sh
60 UNIX Fundamentals Workshop
______________________________________________________________________________
UNIX Fundamentals Workshop 61
______________________________________________________________________________
Why Use vi?
Because you have to.
I‘m sure there is a fancy list somewhere that will tell you all the great reasons why you should use vi
– probably even entire books on the subject – but I won‘t try to convince you here. When it gets right
down to it, the reason you need to know a little vi is because you can count on it being installed on
every customer‘s machine. It comes standard with all UNIX distributions.
You don‘t have to learn a lot about vi , only enough to keep your palms from sweating when you are
sitting at a customer site editing the sasv9.cfg file for their entire installation (no pressure – they have
backups, right ? ).
With that said….let‘s begin the journey into the deep, dark, lonely abyss of vi…..
62 UNIX Fundamentals Workshop
______________________________________________________________________________
vi – an Introduction
vi is unlike other editors. It operates in three distinct modes that will surely make you crazy when
you are first getting started. You‘ll be going along, happy as a clam, thinking that you are actually
typing text into a file – when suddenly you realize that you have actually just used a key sequence
that successfully deleted twenty lines from you file – only you don‘t know how you did it, you‘re not
exactly sure which lines are missing, and you don‘t know how to undo it. So before we get into the
nuts and bolts of vi, you need to commit the following key sequence to memory so you can always
get out of a pickle like the one described above.
The magic sequence to abort any changes and get out of vi is:
[Esc]:q! (escape-colon-lowercase q-exclamation mark)
The [Esc] makes sure that you are in Command Mode, and the [:q!] tells vi to quit the current
file and abandon any changes made. We‘ll learn more about how to undo things later…but for now,
just remember that this is how to get out and abort any changes.
If you just can‘t get vi to behave the way you think it should, check your caps-lock to make sure it is
not on. Like most things Unix, vi is case-sensitive – and for most purposes, caps-lock should NOT be
on.
UNIX Fundamentals Workshop 63
______________________________________________________________________________
The Modes of vi:
Command
Insert [iIoOaA] Mode [:?/] Last Line
Mode Mode
[Enter]
[ESC]
[ESC]
Mode Brief Description Types of Operations Per-
formed
Command mode is the default mode when you start vi. Navigation
Command In this mode, every letter you type is a command. Copying
Mode Deleting Text
Command Mode commands are executed immediately
(they do not require you to hit [enter]).
Insert Mode is invoked by pressing one of the keys
Insert listed as the input mode commands on the next page. Inserting text
Mode Each subsequent key you type once in insert mode will Appending text to a
appear on the screen as text. The ONLY key to get you line
out of insert mode is ESC. Replacing text
Pasting text
This mode is used for file handling and performing
substitution via regular expressions. A colon while in Quitting with/without
Last Command Mode gets you into Last Line Mode – and saving
Line that is usually followed up with a Last Line Mode Writing contents of
Mode Command editor to a new file
Search/Replace
Last Line Mode commands require [enter] to be ex-
ecuted.
64 UNIX Fundamentals Workshop
______________________________________________________________________________
Input Mode Commands
Command Function
i
Inserts text to the left of the cursor. Any existing text will be shifted
right.
a
Appends text to the right of the cursor. Any existing text will be
shifted right.
I
Inserts text at the beginning of the line. Any existing text will be
shifted right.
A Appends text to the end of the line.
o Opens a new line below the current line.
O Opens a new line above the current line.
UNIX Fundamentals Workshop 65
______________________________________________________________________________
Cursor Movement Commands
For all cursor movement commands, you cannot move your cursor where there are no characters. If
you are at the bottom of a file, you cannot move your cursor beyond the last line until you have used
Insert Mode to create a line there. This will make more sense as you try to use the editor.
Also, vi does not typically wrap lines. When you get to the end of a line with a cursor movement
command, your cursor will not magically wrap down and continue along the next line (as most PC
editors do). (The W,B,E, (, ), commands are a few exceptions to this).
Command Function
h Move the cursor one position LEFT
j Move the cursor one position DOWN
k Move the cursor one position UP
l Move the cursor one position RIGHT
Ctrl-u Scroll half page forward.
Ctrl-d Scroll half page backward.
1G Move to beginning of the file
40G Move to line 40
G Move to end of the file
Ctrl-g Display current line number and percentage of file
w Move forward to beginning of next word
Move forward to beginning of next word (space delimited). This will
W also wrap to the next line while searching, while lowercase ―w‖ will
not.
e Move forward to end of current word
E Move forward to end of current word (space delimited).
b Move backward to beginning of last word
B Move backward to beginning of last word (space delmited).
66 UNIX Fundamentals Workshop
______________________________________________________________________________
Cursor Movement Commands (cont’d)
Command Function
0 Move to beginning of current line
$ Move to end of line
) Move to beginning of the next sentence
( Move to beginning of the previous sentence
} Move to next paragraph boundary
{ Move to previous paragraph boundary
UNIX Fundamentals Workshop 67
______________________________________________________________________________
Delete Commands
Command Function
d[mvt_cmd] Delete from current cursor to movement command position
dw Delete up to the next word boundary
d0 Delete from current cursor to beginning of the line
d) Delete from current cursor up until the next sentence boundary
dG Delete from current cursor to the end of the file
d3w Delete 3 words
dd Deletes a line
dj Deletes current line and next line
68 UNIX Fundamentals Workshop
______________________________________________________________________________
Change Commands
Command Function
c[mvt_cmd]
Deletes up to movement command, and immediately goes into insert
mode.
cw Delete up to the next word boundary and go into insert mode
c1G Delete first line, then go into insert mode
cc Deletes a line and goes into insert mode so you can retype it.
Replaces a single character [char] which is directly under the cursor.
r[char] This is the only input mode command that takes you immediately
back out of input mode and into command mode (no [esc] required).
R
Replaces text from the cursor over to the right. Any existing text will
be overwritten.
s Replaces the character under the cursor with any number of characters.
S Replaces the entire line.
UNIX Fundamentals Workshop 69
______________________________________________________________________________
Cut and Paste
vi indeed has cut, paste, and copy - though it can take some getting used to (understatement).
CUT=DELETE:
Every time you do a delete operation in vi, the text is stored in a buffer similar to the clipboard in
Windows. The buffer holds the most recently deleted information (from just 1 command).
Ex: dw (deletes one word)
Ex: dd (deletes current line)
Ex: d5x (deletes 5 characters)
PASTE=P/p:
A lowercase p is used to paste the contents of the cut buffer AFTER the current cursor location.
An uppercase P is used to paste the contents of the cut buffer BEFORE the current cursor location.
P/p command cannot be repeated
Note: Pasting does not remove information from the cut buffer, it just places a copy of it in the file.
The information will remain in the cut buffer until another ―delete‖ operation is used.
COPY=y
y[mvt_cmd]: copies from the current cursor position to the position specified by the movement
command, and places it in the cut buffer (clipboard).
Ex: yw (copies one word)
Ex: yy (copies current line)
Ex: yj (copies 2 lines – current and next)
Making Copies (copy/paste):
1. yank the text with y
2. paste the text with p/P
Moving Text (cut/paste):
1. delete the next with one of the delete commands
2. paste the text with p/P
70 UNIX Fundamentals Workshop
______________________________________________________________________________
Undo & Abort
Yes, it is true that vi has an undo command ―u‖. But it is not a very robust undo by any stretch of the
imagination. For most versions of vi out there, the undo ―u‖ command will only undo the last Input
Mode command (not your last Command Mode command). There is not an undo ―stack‖ like there
is in many Microsoft applications. If you find yourself in a mess and a simple ―u‖ command doesn‘t
fix it….remember, you can always abort any changes you have made to the file with the following
command:
[Esc]:q! (escape-colon-lowercase q-exclamation mark)
Escape ―[Esc]‖ makes sure you are in command mode, and the ―:q!‖ quits without saving any
changes.
When you are getting started with vi, I strongly recommend you use copy/paste instead of cut/paste.
It is just safer that way, and the lack of an ―undo‖ stack will not be nearly as painful for you.
UNIX Fundamentals Workshop 71
______________________________________________________________________________
Repeat Factors & Repeat Last Command (.)
Most of the commands in vi accept a repeat factor. If ―w‖ moves you to the next word, then ―3w‖
would move you three words, ―6w‖ would move you six words, and so on.
There is also a special repeat command, which is just a period ―.‖. This is used to repeat both Input
and Command Mode commands. This might not sound very useful, but it really does come in han-
dy.
To take a simple example, imagine you have just deleted four lines with the command ―4dd‖. Then
to repeat this command in another section of the file, all you have to do is put the cursor where the
lines are you wish to delete and enter ―.‖. (You can use the undo ―u‖ command to undo the repeat if
you wish).
You can also use this to indent a group of lines. You only have to issue the ―i[Tab][Esc]‖ com-
mand one time, and you can then position your cursor on the next line and enter ―.‖ to indent that
line as well.
72 UNIX Fundamentals Workshop
______________________________________________________________________________
Searching a File
Command Function
Find next occurrence of [char] on the current line (moves for-
f[char] ward on the line). This will NOT wrap to next line.
Ex: fC (searches on current line for next ―C‖)
Find next occurrence of [char] on the current line (moves back-
F[char] ward on the line]. This will NOT wrap to next line.
Ex: FC (searches backward on current line for previous ―C‖
Repeats the most recent f or F command. This can be very use-
; ful because most repeat commands do not allow you to repeat
cursor movement – but ―;‖ does.
Search forward in file for [string] (if you get to bottom of the
/[string] file, it will wrap back to the top of the file).
/sas (searches forward in file for next occurrence of ―sas‖)
Search backward in file for [string] (if you get to the top of the
file, it will wrap back to the bottom of the file).
?[string]
?sas (searches backward in file for previous occurrence of
―sas‖)
UNIX Fundamentals Workshop 73
______________________________________________________________________________
Searching and Replacing
Searching and replacing in vi is accomplished with Last Line Mode‘s ―s‖ (for substitute) command.
The syntax is as follows:
:addresss/searchstring/replacestring/[g]
The address can be one or a pair of numbers, separated by a comma:
Ex: To search lines 1-10, the address would be 1,10
Ex: To search lines 50-100, the address would be 50,100
There are some additional special characters that can be used in the address:
. (period) represents the current line number
Ex: .,100 (from here to line 100)
Ex: 0,. (from line 0 to here)
$ (dollar sign) represents the last line number
Ex: .,$ (from here to end of file)
Ex: 1,$ (from line 1 to end of file – the whole file)
% (percent) represents the wholefile
Ex: % is the same as 1,$
By default, the search and replace command will only replace the FIRST occurrence of the search-
string it finds on each line. You have to add the optional [g] at the end of the command in order to
replace ALL occurrence of the search string on each line.
Ex: :%s/sas/SAS/g (searches entire file and replaces all occurrences of sas with SAS)
Ex: :1,10s/9.1/9.1.3/g (searches first 10 lines for 9.1 and replaces it with 9.1.3)
Advanced:
By default, the delimiter in the search/replace command is a forward slash ―/‖. You can actually
use any character you choose. When might you need that? Imagine you have a bunch of occurrences
of /usr/local/sas913 in your file and you need to change that to /bigdisk/sas913 – what would you
do?
Ex: :%s!/usr/local/sas913!/bigdisk/sas913!g
74 UNIX Fundamentals Workshop
______________________________________________________________________________
Quitting and Saving
Command Function
ZZ (upcase ZZ) Save and quit under current default name
:wq Save and quit under current default name
Quit without saving….but only if you haven‘t made any editing
:q changes. You can use this to check to see if you have made any
changes.
:q!
Quit no matter what – aborting any changes that have been made to
the file.
Write contents of editor to file specified by filename. This is like
:w [filename]
the ―Save As‖ in Windows products.
Just like above, but it will overwrite the contents of the file speci-
:w! [filename]
fied if it already exists.
Read file specified by filename and insert its contents under the cur-
:r [filename]
rent line.
UNIX Fundamentals Workshop 75
______________________________________________________________________________
Customizing vi
There are several customizations, shown below, that you can make in your vi session. These settings
will only take effect in the current vi session, but they can be made permanent if placed in the
~/.exrc (or ~/.vimrc for Linux) file.
Command Function
:set all Show all set options that are available to customize
:set ignorecase Ignore case when searching
:set magic Retain meaning of regular expression characters
:set showmode Display message when vi is in input mode
:set sm Momentarily show a match to a )and }
:set ts=n Set tab stops to value of n (default is 8).
:set nu Turns on line numbering (nonu turns it off)
Auto-indent – the next line starts at previous line‘s indented
:set ai level (good for shell programming, but it takes some getting
used to)
76 UNIX Fundamentals Workshop
______________________________________________________________________________
UNIX Fundamentals Workshop 77
______________________________________________________________________________
Exercises: The vilearn Tutorial
In your $HOME/unix_intro/bin directory, you will find a script named vilearn.sh.
When you execute this script, it will take you through a series of vi tutorials that will help you get
started using vi. We will not be able to spend enough time in class to give you warm fuzzies with
using vi – that level of comfort can only be gained by using it for a few weeks. However, we will
need to get through at least the first two tutorials.
prompt> cd $HOME/unix_intro/bin
prompt7> ./vilearn.sh
The following tutorials are available:
-n Tutorial 1 -- Basic Editing
-n Tutorial 2 -- Moving Efficiently
-n Tutorial 3 -- Cutting and Pasting
-n Tutorial 4 -- Inserting Techniques
-n Tutorial 5 -- Tricks and Timesavers
You will be editing your own copy of the tutorial. Enter the number
-n of the tutorial you'd like to see (or q to quit):
1
Copying tutorial……
vi tutorial #1: The Basics
This lesson lasts 10-15 minutes and teaches simple editing. Lines
which begin with >>> mark exercises you should try. When you
want to exit this tutorial type ZZ (type capital Z, twice).
When you type commands in vi they do not appear on the screen. If the
letters you type unexpectedly appear on the screen, press the ESCAPE key.
BASIC CURSOR MOVEMENT
---------------------
To move through the tutorial use ^D (control d) and ^U (control u).
^D Move DOWN one half-screen
(depress the control key and type d)
^U Move UP one half-screen
(depress the control key and type u)
>>> Now type ^D (control d) and ^U (control u) to move down and back up.
………..
78 UNIX Fundamentals Workshop
______________________________________________________________________________