DistributedNetworks DistributedNetworks


vi editing  «Prev  Next»
Lesson 3 Searching for text in vi
ObjectiveUse vi commands to search for text.

Searching for text in vi

In this lesson, you will learn how to search for text. The vi editor provides several commands for locating text:
Command Action
/pattern Search forward for pattern
?pattern Search backward for pattern
n Repeat search in the same direction
N Repeat search in the opposite direction

The / and ? commands behave somewhat like ex commands, because the / and ? appear on the status line. Also, you must press Enter after typing the pattern. After finding a pattern using the / or ? command, you can use n or N to search for the next occurrence. The n and N commands are regular vi commands. They take effect immediately, with no need to press Enter.
The vi program understands regular expression[1] syntax. In vi, search patterns are actually regular expressions. This means you can use metacharacters such as ., [ ], *, ^ and $. They have the same meanings as when they are used with grep commands.
In vi, regular expressions do not need to be quoted, because vi provides its own environment separate from the shell. However, you must still type a backslash before a character if you want to disable its meaning as regular expression syntax. For example, use \. to search for an actual period.
The following SlideShow demonstrates text searches in vi:
Text 1
1) First open the phonelist file.
Text 2
2) When you press/ to start a forward search, your cursor goes to the status line.
Text 3
3) Press Enter and the cursor moves to the text 28, which is the first instance that the regular expression 2 matches.
Text 4
4) To search again, press n, a command that does not appear on the screen.
Text 5
5) Press? to a start a backward search. Notice the cursor again goes to the status line.
Text 6
6) Press Enter and the backward search begins from the last cursor position

Searching Text using-special Characters
In the next lesson, you will learn how to use the :ab command to abbreviate text.

Searching Text in vi- Exercise

Click the Exercise link below to practice finding text in vi.
Searching Text in vi- Exercise
[1]: regular expression: A regular expression describes a pattern using literal characters and optional metacharacters known as regular expression syntax.