You are on page 1of 23

Lecture- 6

Vi Editor ( search, replace, G


command and some exercises)
Search in File
• One of the most useful ways to move around quickly in a large file is by
searching for text, or more properly, a pattern of characters.
• The search command is the special character / (slash). When you enter a
slash, it appears on the bottom line of the screen; you then type in the
pattern that you want to find: /pattern.
• A pattern can be a whole word or any other sequence of characters
(called a “character string”).
• For example, if you search for the characters red, you will match red as a
whole word, but you’ll also match occurs of red in a word.
• You execute the search by typing the command key, then string followed
by RETURN.
• vi searches forward with the slash (/) key or backward with the question
mark key (?).
Example of search pattern
• Using the file practice, here’s how to move the cursor by searches:
Keystrokes Results
/edits With a screen editor you can scroll the
page, move the cursor, delete lines
results of your edits as you make them.
Search for the pattern edits. Press ENTER to enter. The cursor moves directly to
that pattern.
?scr With a screen editor you can scroll the
page, move the cursor, delete lines, insert
results of your edits as you make them.
– Search for the pattern scr. Press ENTER to enter. Note that there is no space
after scr.
• Note that you can give any combination of characters; a search does not have to
be for a complete word.
• In both cases, the search wraps around to the beginning or end of the file, if
necessary.
Repeating Searches
• The last pattern that you searched for stays available throughout your editing
session. After a search, instead of repeating your original keystrokes, you can
use a command to search again for the last pattern:
• n
– Repeat search in same direction.
• N
– Repeat search in opposite direction.
• / ENTER
– Repeat search forward.
• ? ENTER
– Repeat search backward.
• Since the last pattern stays available, you can search for a pattern, do some
work, and then search again for the same pattern without retyping it by using
n, N, /, or ?.
Example
• To continue with the previous example, since the pattern scr is still available for search, you
can do the following:
Keystrokes Results
n With a screen editor you can scroll the
page, move the cursor, delete lines, insert
results of your edits as you make them.
Move to the next instance of the pattern scr (from screen to scroll) with the n (next)
command.
?you With a screen editor you can scroll the
page, move the cursor, delete lines, insert
results of your edits as you make them.
Search backward with ? from the cursor to the first occurrence of you. You need to press
ENTER after typing the pattern.
N With a screen editor you can scroll the
page, move the cursor, delete lines, insert
results of your edits as you make them.
Repeat the previous search for you but in the opposite direction (forward).
Wrapscan
• When vi reaches the end of the text, it continues searching from
the beginning. This feature is called wrapscan.
• Sometimes you want to find a word only if it is further ahead; you
don’t want the search to wrap around earlier in the file.
• vi has an option, wrapscan, that controls whether searches wrap.
You can disable wrapping like this:
:set nowrapscan
• When nowrapscan is set and a forward search fails, the status line
displays the message:
Address search hit BOTTOM without matching pattern
• When nowrapscan is set and a backward search fails, the message
displays “TOP” instead of “BOTTOM.”
Changing through searching

• You can combine the / and ? search operators with the commands that change
text,such as c and d.
• Continuing with the previous example: we have practice file :
With a screen editor you can scroll the
page, move the cursor, delete lines, insert
results of your edits as you make them.
Keystrokes Results
d?move With a screen editor you can scroll the
page, your edits as you make them.
Delete from before the cursor up to and through the word move.
Special Character
• Vi supports a few special characters, which act as
wildcards or search – exclusion.
• The [cccc] stands for any character in the bracket; it
could be g, h,i.
• The special characters are : ‘$’, ‘.’, ’*’, ‘[]’, ‘^’, ‘\’.
• When specifying search strings, you will sometimes
want to search for one of the special characters.
• To do so, type a backslash (\) immediately before the
special character. For example: \$5 matches “$5.00.” or
to specify a single backslash, type \\.
Metacharacters Used in Search Patterns
• . (period, dot)
– Matches any single character except a newline. Remember that spaces are treated as
characters. For example, p.p matches character strings such as pep, pip, and pcp.
• *
– Matches zero or more (as many as there are) of the single character that
immediately precedes it. For example, bugs* will match bugs (one s) or bug (no s). (It
will also match bugss, bugsss, and so on.)
– The * can follow a metacharacter. For example, since . (dot) means any character, .*
means “match any number of any character.”
• ^
– When used at the start of a regular expression, requires that the following regular
expression be found at the beginning of the line. For example, ^Part matches Part
when it occurs at the beginning of a line, and ^... matches the first three characters
of a line. When not at the beginning of a regular expression, ^ stands for itself.
• $
– When used at the end of a regular expression, requires that the preceding
regular expression be found at the end of the line; for example, here:$ matches
only when here: occurs at the end of a line. When not at the end of a regular
expression, $ stands for itself.
• \
– Treats the following special character as an ordinary character. For example, \.
matches an actual period instead of “any single character,” and \* matches an
actual asterisk instead of “any number of a character.” The \ (backslash)
prevents the interpretation of a special character. This prevention is called
“escaping the character.” (Use \\ to get a literal backslash.)
• []
– Matches any one of the characters enclosed between the brackets. For
example, [AB] matches either A or B, and p[aeiou]t matches pat, pet, pit, pot,
or put. A range of consecutive characters can be specified by separating the
first and last characters in the range with a hyphen. For example, [A-Z] will
match any uppercase letter from A to Z, and [0-9] will match any digit from 0 to
9.
Searching with special character
Usage Action Example matches
[cccc] Match any of the characters /sa[fn] Safe, santuary
cccc
[^cccc] Match all characters except /[^a]nd Behind, ground
cccc
[c1-c2] Match any characters between /[d-h]er Thunder,
c1 and c2 weathered
\<cccc Match word beginning with /\<eac Each
cccc
cccc\> Match words ending with cccc /und\> Ground, round
Match lines beginning with /^in In foot and….
^cccc cccc
. Match any single character /i.l Grimly, hills
c* Match the character c zero or /mb*d Scrambled,
more times rumbled
Search and Replace
• Vi can also search and replace, which means finding instances of a given
string and replacing them with a new string.
• This search-and-replace operation is actually an ex command, and it has
the following form:
– :line1, line2s/ oldstring /newstring
• If you only give line1 and omit the comma, then the command only
affects that line.
• If you give no line number, the command affects current line.
• The search-and-replace command only finds the first occurrence of
oldstring on the line.
• You can repeat a search-the replace on the current line by typing an
ampersand (&). To repeat it on a different line or group of line, type:
– :linenumber& or : line1,line2&
Example of search and replace
• Lets replace the word “heavens” with “sky.”
• The file content is
our heavens fell on ground
Now type:
:s/heavens/sky and press Return
The first instance of “heavens” becomes “sky”. Now
press the ampersand (&) to repeat the command.
• Now if it is on 16th line than you can type as:
– :16s/heavens/sky
A powerful search and replace
• The ex command g (for global) can be used with s (substitute)
to find and replace every occurrence of a string pattern in an
entire file.
• The syntax of the global command is:
:g/string/commands
– The global command finds each line in the file that has
string in it and then applies the command to it.
• You can combine the global and substitute it in the following
manner:
:g/oldstring/s//newstring/g or :%s/oldstring/newstring/g
Substitutions
• The simplest way to do substitutions over a range of lines, or throughout the file, is to
use the s colon command.
• The basic form of this command is the following:
• :n1,n2s/old/new/gc
– n1 is the beginning line
– n2 is the ending line number
– s means to substitute text matching the pattern (old) with text specified by (new)
– g (global) is optional. It indicates you want to substitute all occurrences on the indicated lines.
– If you not use g, the editor substitutes only the first occurrence on the indicated lines.
– c (confirm) is optional. It indicates you want to confirm each substitution before vi completes it.
• From Command Mode
• :%s/old/new/g
– Substitutes old with new throughout the file
• :.,$s/old/new/g
– Substitutes old with new from the current cursor position to the end of the file
• :^,.s/old/new/g
– Substitutes old with new from the beginning of the file to the current cursor position
• :&
• Repeats the last substitute (:s) command
Example
• For example:
Suppose your subroutine names begin with the prefixes mgi,
mgr, and mga and If you want to save the prefixes, but want
to change the name box to square:
mgibox routine,
mgrbox routine,
mgabox routine,
Keystrokes Result
:g/mg[ira]box/s/box/square/g mgisquare routine,
mgrsquare routine,
mgasquare routine,
Different Substitutions
Example 1. Substitute all occurrences of a text with another text in the whole
file
:%s/old-text/new-text/g
Example 2. Substitute of a text with another text within single line.
:s/I/WE/gi
Example 3. Substitution of a text with another text within a range of lines
:1,10s/helo/hello/g
Example 4. Substitution of a text with another text only the 1st X number of
lines
:s/helo/hello/g 4
Example 6. Substitute only the whole word and not partial match
:s/\<his\>/her/ g
Example 7. Substitute either word1 or word2 with a new word using regular
expression
:%s/\(good\|nice\)/awesome/g
Current Line Searches
• There are also miniature versions of the search
commands that operate within the current line.
• The command fx moves the cursor to the next instance of
the character x (where x stands for any character).
• The command tx moves the cursor to the character
before the next instance of x.
• Semicolons can then be used repeatedly to “find” your
way along.
• The inline search commands are summarized here. None
of these commands will move the cursor to the next line:
Current Line search

With any of these commands, a numeric prefix n locates the nth occurrence.

Commands Searches
fx Find (move cursor to) next occurrence of x in the line, where x
stands for any character.
Fx Find (move cursor to) previous occurrence of x in the line.
tx Find (move cursor to)one character before next occurrence of x
in the line.
Tx Find (move cursor to) one character after previous occurrence
of x in the line.
; Repeat previous find command in same direction.
, Repeat previous find command in opposite direction.
Example for searching within a line
• Suppose you are editing in practice, on this line:
With a screen editor you can scroll the.
Keystrokes Results
fo With a screen editor you can scroll the.
Find the first occurrence of o in your current line with f.
; With a screen editor you can scroll the.
Move to the next occurrence of o with the ; command (find next o).
to With a screen editor you can scroll the.
move to the one character before ‘o’ (find next o and point to one character
before that)
dt. With a screen editor you can scr.
it will delete text from current cursor position to the one character before the
occurrence of ‘.’
Movement by Line Number
• Lines in a file are numbered sequentially, and you can move
through a file by specifying line numbers.
• Line numbers are useful for identifying the beginning and end of
large blocks of text you want to edit.
• Line numbers are also useful for programmers, since compiler
error messages refer to line numbers.
• The command CTRL-G causes the following to be displayed at the
bottom of your screen: the current line number, the total number
of lines in the file, and what percentage of the total the present
line number represents.
• For example, for the file practice, CTRL-G might display:
"practice" line 3 of 6 --50%--
The G (Go To) Command
• You can use line numbers to move the cursor through a file.
• The G (go to) command uses a line number as a numeric
argument and moves directly to that line.
• For example, 25G moves the cursor to the beginning of line
25.
• G without a line number moves the cursor to the last line of
the file.
• Typing two backquotes (``) returns you to your original
position (the position where you issued the last G
command), unless you have done some edits in the
meantime.
Review of vi Search Commands
Movement Command
Search forward for pattern /pattern
Search backward for pattern ?pattern
Repeat last search n
Repeat last search in opposite direction N
Repeat last search forward /
Repeat last search backward ?
Move to next occurrence of x in current line fx
Move to previous occurrence of x in current line Fx
Move to just one character before next occurrence of x in current tx
line
Move to just one character after previous occurrence of x in Tx
current line
Repeat previous find command in same direction ;
Repeat previous find command in opposite direction ,
Go to given line n nG

You might also like