5.8 Search and Replace

   

Search and replace is a necessary editing feature found in all good editors. If you want to find a text pattern in vi , you can use the /text command, where text is the string you want to search. This command searches the text in the forward direction from the current cursor position. You can search in the backward direction if you replace / with ? in the command. To repeat the search once you find a string, just use / or ? without typing the string again.

You can also replace text after a search is made. For example, if you want to replace the word "Atlanta" with "Chicago," you can use the command :s/Atlanta/Chicago/ to search for the next occurrence of "Atlanta" and then replace it with "Chicago." You can use the search-and-replace feature in as many lines as you want or in all of the file. Table 5-6 shows a summary of search-and-replace commands used in vi .

Table 5-6. Text Searching and Replacing Commands
Command Effect
/text Search text in forward direction starting from current cursor location.
?text Search text in backward direction starting from current cursor location.
/ Repeat previous search in forward direction.
? Repeat previous search in backward direction.
n Repeat search in the same direction.
N Repeat search in the opposite direction.
:s/oldtext/ newtext Search oldtext in the forward direction and replace it with newtext.
:m,ns/oldtext/newtext Search oldtext in the forward direction from line m to line n and replace it with newtext.
:s/oldtext/newtext/g Search oldtext in the entire file and replace it with newtext.
/<space>text If you put a space between the / and the text to be searched, only whole words are searched.
/^text Search text only in the beginning of a line.
/text$ Search text only in the end of a line.
/ (More than one word) Use parenthesis to search multiple words.

Escape characters have special meaning in vi . For example, the $ character is used to show the end of a line. If you want to search the $ sign in vi , you need to put a backslash ( \ ) in front of it to tell vi that it should be considered an ordinary character and no special meaning of $ should be taken. You will use " /\$ " to search for the $ character in a file. Similarly, other special characters ( ^ , * , / , .) must also be escaped.


   
Top


HP Certified
HP Certified: HP-UX System Administration
ISBN: 0130183741
EAN: 2147483647
Year: 2000
Pages: 390
Authors: Rafeeq Rehman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net