17CS35 - Module - 3 Vi Editor and Shell VTUPulse.com
17CS35 - Module - 3 Vi Editor and Shell VTUPulse.com
Shell Programming
MODULE : 3
The vi editor. Basics. The .exrc file. Different ways of invoking and quitting vi. Different modes
of vi. Input mode commands. Command mode commands. The ex mode commands. Illustrative
examples Navigation commands. Repeat command. Pattern searching. The search and replace
command. The set, map and abbr commands. Simple examples using these commands.
The shells interpretive cycle. Wild cards and file name generation. Removing the special
meanings of wild cards. Three standard files and redirection. Connecting commands: Pipe.
Splitting the output: tee. Command substitution. Basic and Extended regular expressions. The
grep, egrep. Typical examples involving different regular expressions.
Topics from chapters 7, 8 and 13 of text book 1. Topics from chapter 2 and 9 ,10 of
text book 2
THE VI EDITOR
vi BASICS
Invoking vi editor
vi <filename>
In all probability, the file doesn’t exist, and vi presents you a full screen with the filename
shown at the bottom with the qualifier, [New file].
The cursor is positioned at the top and all remaining lines of the screen show a ~. They
are non-existent lines.
The last line is reserved for commands that you can enter to act on text. This line is also
used by the system to display messages.
When file is opened in a vi editor, by default it will be opening in a command mode.
This is the mode where you can pass commands to act on text, using most of the keys
of the keyboard.
This is the default mode of the editor where every key pressed is interpreted as a
command to run on text. You will have to be in this mode to copy and delete text.
To enter text, you must switch to the input mode. First press the key i, and moved to
input mode and ready to input text. Subsequent key depressions will then show up on the
screen as text input.
After text entry is complete, the cursor is positioned on the last character of the last line.
This is known as current line and the character where the cursor is stationed is the
current cursor position. This mode is used to handle files and perform substitution.
Command Mode:
When user starts up vi editor, user are in “command mode”. The default mode of the
editor where every key pressed is interpreted as a command to run on text.
This mode allows to copy, delete text (edit files) and to move to any other modes. When
keys are pressed in this mode it simply performs functions, it doesn’t displayed on the
screen. When you are in command mode, letters of the keyboard will be interpreted as
commands.
Some of the command mode commands are : To delete a text command x is used, to
delete entire line use dd command, to put the character use P or p command, to yank the
text use y command, use of yy copies entire line, to undo the recent actions use u
command.
When user in a command mode, the letters of the keyboard will be interpreted as
commands. These commands are one or two characters long, and can be entered with
few keystrokes.
Once the editing is finished save the changes by moving to ex mode by using :w
command.
Unnecessary pressing of [Esc] in this mode sounds a beep but also conforms you are in
this mode.
As shown in the figure, from command mode user can get into the input mode by
giving any of these keys i a I A o O r R s S.
The control can be brought back to the command mode by using the <Esc> key.
From within the command mode the user can get into the ex mod by using the :
Input mode:
To enter the text, have to change from default command mode to Input mode
Every key pressed after switching to this mode actually shows up as text. This mode is
invoked by pressing one of the keys among i a I A o O r R s S.
In the above command list i and I stands for insertion, a and A stands for appending the
text, o and O stands for opening a new blank new line, r and R stands for replacement of
text, s and S stands for substitution of new text. This mode permits the insertion of new
text, appending the existing text and replacement, substitution of text.
The i can be used to insert text anywhere in a line, I insert text only at the beginning of a
line.
To append text to the right of the cursor position use a. To append text at the end of the
line use A.
To open a line below the current line use o. To open a line above the current line use O.
To replace one single character with another, user r followed by the character that
replaces the one under the cursor.
To replace more than a single character use R followed by the text and then press [Esc].
To replace a single character with multi-character text, move the cursor to the point and
then press s.
The S replaces the entire line irrespective of the cursor position. After pressing S, the
entire line vanishes from sight. Key in your text, and then press [Esc].
As shown in the figure, at any time user can go back to the command mode from insert
mode by pressing the <Esc> key.
Ex mode (Last line mode):
This mode is also known as the last-line mode and allows the user to use the command
in the bottom line in vi screen.
This mode is used to handle files (like saving) and perform substitution.
Pressing a : in the command mode invokes this mode and cursor moves to the bottom of
the screen.
The bottom line of the vi screen is called the command line and it’s used to display the
entered ex mode commands. The commands entered in this mode are displayed in the
command line, the last line. Anything entered in front of the colon : prompt it is taken as
an ex command.
Some of the sample ex mode commands are : :w to save the file contents, command
:wq used to save and quit the editor, :q to just quit the editor, :q! to quit the editor by
discarding the changes made
After inserting ex mode command press [Enter], so it moved back to command mode.
After the command is run then it’s moved back to the default command mode.
As shown in the figure; when user starts up vi editor, user is in “command mode”. From
command mode user can enter to input mode by pressing I,i,a,A,s,S,R,r,O,o commands.
From input mode user can move back to command mode by pressing [esc]. From
command mode to ex mode is invoked by pressing :. From ex mode pressing [enter]
move to the command mode.
Command Function
i Inserts text before the current character
I Inserts text at the beginning of current line
a Appends text after the current character
A Appends text at the end of the current line
o Opens a line under the current line and inserts supplied text in it.
O Opens a line above the current line and inserts supplied text in it.
r Replaces the current character at the cursor with the new one
R Replaces a set of characters with a new set of characters
s Substitute the current character with the supplied text
S Substitute the current line with the supplied text
OR
Command Function
Insert text to the left of cursor (existing text shifted right)
i
Append text to right of cursor (existing text shifted right)
a
Insert text at beginning of line (existing text shifted right)
I
Append text at the end of line
A
Opens a line below
o
Opens a line above
O
Replaces single character under cursor with ch
rch
Replaces text from cursor to right(existing text overwritten)
R
Replaces single character under cursor with any number of character
s
NAVIGATION
Functions of different commands in command mode are described in this section. A command
mode command doesn’t show up on the screen but simply performs the function.
Movement in the Four Direction (h,j,k and l)
Vi provides the keys h,j,k and l to move the cursor in the four directions. These keys are placed
adjacent to one another in the middle row of the keyboard. Without a repeat factor, these keys
move the cursor by one position.
Use these keys for moving the cursor vertically:
k Moves the cursor UP
j Moves cursor DOWN
To move the cursor along a line, use these commands:
h Moves cursor LEFT
l Moves cursor RIGHT
The repeat factor can be used as a command prefix with all these four commands.
4k moves the cursor 4 lines up and 20h takes it 20 characters to the left.
Summary Table
k moves cursor up UP
Refer class notes for example on scrolling diagram on page no 132 in book
Moving to the beginning or end of a line is a common requirement. It is achieved by keys 0,| and
$.
To move to the first character of a line use 0 or |
0 or | 30| moves cursor to column 30
The | takes a repeat factor and using that, it is possible to position the cursor on a certain column.
To position the cursor on column 30, use 30|.
$ moves to the end of the current line
$ Moved to the end of the current line
The use of these commands along with b, e, and w is allowed
Refer class notes for example on scrolling diagram on page no 133 in book
Scrolling
Faster movement can be achieved by scrolling text in the window using the control keys. The
two commands for scrolling a page at a time are
ctrl-f scrolls forward
ctrl-b scrolls backward
10ctrl-f scroll 10 pages and navigate faster
ctrl-d scrolls half page forward
ctrl-u scrolls half page backward
5ctrl-d scrolls 5 pages forward.
Absolute Movement
To know the current line number can press [Ctrl-g]:
“/etc/passwd” [Read Only] line 45 of 125 ---45%---
The cursor is on line 45 (45% of 125), and this read only file has 125 lines in all.
Use G command with line number as repeat factor to locate the offending lines.
To move to the 40th line, use
40G Goes to line number 40
To move to the beginning of the file, use
1G Goes to line number 1
The end of the file is reached by simply using
G Goes to end of file
Summary Table
Command Function
Moves back to the beginning of a word
b
EDITING TEXT
Deleting text ( x and dd )
The simplest text deletion is achieved with the x command. This command deletes the character
under the cursor.
Move the cursor to the character that needs to be deleted and then press x,
The character under the cursor gets deleted the text on the right shifts left to fill up the space.
Repeat factor also applies here. 4x deletes the current character as well as three characters from
the right.
Deletion of the left character can be handle by the “ X ” command .
Entire lines can be deleted(removed) with “ dd “ command. Here also repeat factor applies.10dd
deletes the current line and 9 lines below it.
This is the vi full-screen editor from UCB
x
Coping text(y,p)
Vi uses the term yanking for copying the text. In vi extracting a copy of the required text is
known as yanking.
y => it copies the single character
yy => it copies the entire line – copies the current line
10yy=> it copies the current line & below 9 line.
This copied text has to be placed at the new location. The put commands are the same – p and P.
Joining Lines (J)
To loin the current line and the line following it, use J. This command will join the 2 lines by
deleting the newline character which is present between the two lines
4J 4J joins following 3 lines with current one
Summary Table
Command Meaning
p Puts the deleted(or yanked) text after the current character
P Puts the deleted(or yanked) text before the current character
x Deletes the current character
y Yanks a text object.
X Deletes the character before the cursor
d Deletes a line or a range of lines
u Undoes only the last edit
? Pattern [Enter]
The sequence searches backward for the most previous instance of the pattern, the wraparound
features also applies here but in the reverse direction. i.e after the beginning of the file is
reached the search continues from the end of the file. Both of these command are command
mode commands.
Repeating the last pattern search ( n and N)
To repeat a search in the direction the previous search was made with /and ? use n.
n Repeats search in same direction of original search
n => the user can press “ n ” repeatedly to scan all instances of the string. Cursor is positioned at
the beginning of the pattern
N => it reverses the direction pursued by n , i.e. this is used to retrace the search path of n
Summary table
Command Function
/pat Searches forward for the pattern
n Repeat search in same direction along which previous search was made
N Repeat search in REVERSE direction along which previous search was made
Here the source_pattern is replaced with target_pattern in all lines specified by address.
Address can be one or a pair of numbers. 1,$ -> addresses all lines in a file i.e. from 1 st line to
last line. Common flag is “ g “ , which carries out the substitution for all occurrences of the
pattern in line.
Example: :1,$s/csa/csb/g Searches for csa and its substituted by csb in entire file
If we omit the “ g” flag , the substitution will be carried out only for the first occurrence in each
addressed lines.
The target pattern is optional. If it is not mentioned then it will delete all instances of the source
pattern in all lines matched by the address.
Example: 1,50 s/ note / /g deletes note everywhere in line 1 to 50
The range of lines that are to be affected by the substitution can also be specified.
settings become permanent. Whenever a file is opened using vi, vi looks for the .exrc file in the
home directory of the user. If present, it reads the file and applies the settings in the file being
opened. And hence any customization we would like to have in the file should be put in this.
.exrc is a file located in $HOME/ .exrc, which holds many ex mode commands and a
series of set commands. Execution of these provides a suitable working environment with the vi.
The vi reads file $HOME/.exrc on startup. This file helps to create abbreviations, redefine the
keys to behave differently and also make variable settings.
Typical entries of a .exrc file is depicted as
$ cat.exrc
set number
ab p printf
ab s scanf
map x :wq^M
When file is opened in vi editor, the .exrc file in the home directory will be read and all the
commands present in it will be executed, thus building up the required editing environment.
The command :set autoindent automatically indents every new line keyed in by the user with
one or several tabs. Auto indenting can be cancelled by using the command :set noautoindent
Options that are set using set commands are applicable only to those sessions in which they are
given. If the user wants the settings to be applicable permanently, relevant settings must be set
using corresponding commands in the .exrc file.
Command Meaning
:set number Displays lines with line numbers on the left side.
Map Command
Assign existing vi commands to a custom key or define own custom commands. Using this
command one can connect one or more commands to a single key. This process is known as
mapping. Such a facility allows the user to perform complex editing tasks with a single
keystroke.
For example: map Q :q!
This command maps the Q key with the quit operation. So, whenever the user wants to quit the
file, instead of typing ':q!', the user can simply type 'Q' from the escape mode.
The ab command
This is also an ex mode command and is used to have short hand abbreviations for commonly
used expressions or the input text.
For example while writing the C programs, the printf and scanf words can be abbreviated using
the single characters p and s respectively as shown below.
:ab p printf
:ab s scanf
When the abbreviated character p followed by a space character or the enter key is used the text
printf appears at the place of p.
So ab command helps to define abbreviations and that are expanded into a specific sequence of
characters when they are encountered while users are typing text in Insert mode. Frequently used
words can be abbreviated. For example, say, a user uses the word 'include' lot many times. The
user can create an abbreviation 'inc' for the word include.
ab inc include
Whenever user type 'inc' followed by a space in a file, it automatically gets converted to 'include'.
While abbreviations set during a session are valid only for that session If the user wants the
abbreviations to be applicable permanently then corresponding abbreviations entries must be
made in .exrc file.
********************Review Questions: University Questions ******************
Explain what the following commands do i) :.,10w foo ii) :$w! foo. In
which mode are the commands executed.
How do commands u and U differ? When will U fail to work?
Explain the ex and input mode vi editor commands with example
With example explain the different navigation commands
Illustrate how to search and replace a pattern with example
THE SHELL
Introduction
Shell acts as both a command interpreter as well as a programming facility.
Numerous other shells are available. Some of the more well known of these may be on your Unix
system: the Korn shell, ksh, by David Korn, C shell, csh, by Bill Joy and the Bourne Again SHell,
bash, from the Free Software Foundations GNU project, both based on sh, the T-C shell, tcsh, and
the extended C shell, cshe, both based on csh.
Even though the shell appears not to be doing anything meaningful when there is no activity at the
terminal, it swings into action the moment you key in something.
The following activities are typically performed by the shell in its interpretive cycle:
The shell issues the prompt and waits for you to enter a command.
After a command is entered, the shell scans the command line for meta characters and
expands abbreviations (like the * in rm *) to recreate a simplified command line.
It then passes on the command line to the kernel for execution.
The shell waits for the command to complete and normally can’t do any work while the
command is running.
After the command execution is complete, the prompt reappears and the shell returns to
its waiting role to start the next cycle. You are free to enter another command.
The meta characters that are used to construct the generalized pattern for matching filenames
belong to a category called wild-cards. The following table lists them:
Wild-card Matches
* Any number of characters including none
? A single character
[ijk] A single character – either an i, j or k
[x-z] A single character that is within the ASCII range of characters x and z
[!ijk] A single character that is not an i, j or k (Not in C shell)
[!x-z] A single character that is not within the ASCII range of the characters x and z (Not in C
Shell)
{pat1,pat2...} Pat1, pat2, etc. (Not in Bourne shell)
Examples:
To list all files that begin with chap, use, $ls chap*
To list all files whose filenames are six character long and start with chap, use , $ls chap??
Note: Both * and ? operate with some restrictions. for example, the * doesn’t match all files
beginning with a . (dot) or the / of a pathname. If you wish to list all hidden filenames in your
directory having at least three characters after the dot, the dot must be matched explicitly.
$ ls .???*
However, if the filename contains a dot anywhere but at the beginning, it need not be matched
explicitly.
Similarly, these characters don’t match the / in a pathname. So, you cannot use, $cd /usr?local to
change to /usr/local.
Examples:
You can negate a character class to reverse matching criteria. For example,
- To match all filenames with a single-character extension but not the .c ot .o files, use *.[!co]
- To match all filenames that don’t begin with an alphabetic character, use [!a-zA-Z]*
For instance, if we have a file whose filename is chap* (Remember a file in UNIX can be names
with virtually any character except the / and null), to remove the file, it is dangerous to give
command as rm chap*, as it will remove all files beginning with chap. Hence to suppress the
special meaning of *, use the command rm chap\*
$cat chap0\[1-3\]
A filename can contain a whitespace character also. Hence to remove a file named My
Documend.doc, which has a space embedded, a similar reasoning should be followed:
Quoting is enclosing the wild-card, or even the entire pattern, within quotes. Anything within
these quotes (barring a few exceptions) are left alone by the shell and not interpreted. When a
command argument is enclosed in quotes, the meanings of all enclosed special characters are
turned off.
Examples:
Standard input: The file (stream) representing input, connected to the keyboard.
Standard output: The file (stream) representing output, connected to the display.
Standard error: The file (stream) representing error messages that emanate from the
command or shell, connected to the display.
A file is opened by referring to its pathname, but subsequent read and write operations identify
the file by a unique number called a file descriptor. The kernel maintains a table of file descriptors
for every process running in the system. The first three slots are generally allocated to the three
standard streams as,
0 – Standard input
1 – Standard output
2 – Standard error
Examples:
Assuming file2 doesn’t exist, the following command redirects the standard output to file
myOutput and the standard error to file myError.
1. Directory-oriented commands like mkdir, rmdir and cd, and basic file handling
commands like cp, mv and rm use neither standard input nor standard output.
2. Commands like ls, pwd, who etc. don’t read standard input but they write to standard
output.
3. Commands like lp that read standard input but don’t write to standard output.
4. Commands like cat, wc, cmp etc. that use both standard input and standard output.
Commands in the fourth category are called filters. Note that filters can also read directly from
files whose names are provided as arguments.
Example:
To perform arithmetic calculations that are specified as expressions in input file calc.txt and
redirect the output to a file result.txt, use
$ command1 | command2
$ rm temp
Examples
Creating a tee
tee is an external command that handles a character stream by duplicating its input. It saves one
copy in a file and writes the other to standard output. It is also a filter and hence can be placed
anywhere in a pipeline. Example:-
The following command sequence uses tee to display the output of who and saves this output in a
file as well.
Above command displays currently logged in users on standard output and writes a copy to
users.lst
Command substitution
The shell enables the connecting of two commands in yet another way. While a pipe enables a
command to obtain its standard input from the standard output of another command, the shell
enables one or more command arguments to be obtained from the standard output of another
command. This feature is called command substitution.
Example:
Observe the use of backquotes around date in the above command. Here the output of the
command execution of date is taken as argument of echo. The shell executes the enclosed
command and replaces the enclosed command line with the output of the command. Similarly the
following command displays the total number of files in the working directory.
Observe the use of double quotes around the argument of echo. If you use single quotes, the
backquote is not interpreted by the shell if enclosed in single quotes.
You often need to search a file for a pattern, either to see the lines containing ( or not containing)
it or to have it replaced with something else. This chapter discusses two important filters that are
specially suited for these tasks- grep and sed. This chapter also takes up one of the fascinating
features of UNIX – regular expressions (RE).
To discuss all the examples in this chapter we use following emp.lst as the reference file.
$ cat emp.lst
grep scans its input for a pattern displays lines containing the pattern, the line numbers or
filenames where the pattern occurs. The command uses the following syntax:
grep searches for pattern in one or more filename(s), or the standard input if no filename is
specified.
The first argument (except the options) is the pattern and the remaining arguments are filenames.
Examples:
here, grep displays 4 lines containing pattern as “sales” from the file emp.lst.
here, grep silently returns the prompt because no pattern as “president” found in file emp.lst.
when grep is used with multiple filenames, it displays the filenames along with the output.
grep options:
The below table shows all the options used by grep.
Option Significance
-i Ignores case for matching
-v Doesn't display lines matching expression
-n Displays line numbers along with lines
-c Displays count of number of occurrences
-l Displays list of filenames only
-e exp Matches multiple patterns
-f filename Takes patterns from file, one per line
-E Treats patterns as an ERE
-F Matches multiple fixed strings
Examples:
When you look for a name but are not sure of the case, use the -i (ignore) option.
The -v option selects all the lines except those containing the pattern.
It can play an inverse role by selecting lines that does not containing the pattern.
The -n(number) option displays the line numbers containing the pattern, along with the
lines.
here, first column displays the line number in emp.lst where pattern is found
The -c(count) option counts the number of lines containing the pattern.
With the -e option, you can match the three agarwals by using the grep like this:
You can place all the patterns in a separate file, one pattern per line.
$ cat patterns.lst
director
manager
chairman
The below table shows the BASIC REGULAR EXPRESSION(BRE) character set-
Examples:
The *
The * (asterisk) refers to the immediately preceding character.
Here, it indicates that the previous character can occur many times, or not at all.
The Dot
A . matches a single character.
$ ls -l | grep '^d'
egrep is another alternative to use all the ERE characters without -E option.
This ERE uses some additional characters set shown in below table-
Expression Significance
ch+ Matches one or more occurrences of character ch
ch? Matches zero or one occurrence of character ch
exp1 | exp2 Matches exp1 or exp2
GIF | JPEG Matches GIF or JPEG
(x1|x2)x3 Matches x1x3 or x2x3
(hard|soft)ware Matches hardware or software
Examples:
The + and ?