Searching and Replacing in vi


Searching and Replacing in vi

One of vi's better features (and advantages over pico) is that it allows you to search and replace throughout entire files. As shown in the next sections, you can just find a specific string of text (a regular expression, in Unix lingo; see Figure 4.14), or you can find the text and replace it with other text, as in Figure 4.15.

Figure 4.14. Searching for text in vi is quick and reliable.


Figure 4.15. Replacing text in vi requires a bit of arcane syntax, but you get used to it quickly.


To Find a String of Text in vi:

1.

vi hairyspider

For starters, access vi and a specific file.

2.

/spider

Enter command mode, then type / followed by the text you're looking for. Here, we're looking for "spider," but you may be looking for "the fly" or "wiggled and jiggled and tickled inside her." Or whatever.

3.



Press this to find the first occurrence of the term. Press to find the next one.

To Search and Replace in vi:

1.

vi hairyspider

For starters, access vi and a specific file.

2.

:%s/swallowed the fly/swallowed a spider to catch the fly/

Enter :%s/ plus the text to find, followed by the replacement text, as in Figure 4.15. Here, we replace "swallowed a fly" with "swallowed a spider to catch the fly," but perhaps you might forego the spider and simply go for some antacid.

Tips

  • A great use for the search-and-replace feature is if you end up with DOS text files in your Unix account (through uploading a text file from a DOS or Windows machine as a binary file, most likely). If you view DOS files through a Unix shell, all the lines within the file will end with ^M. But if you try to type ^M when you're doing a search and replace, the ^M won't show up. What to do? Press , then . Just search and replace with :%s/ //g. The command "escapes" the following character, so you can type it without actually doing what the command would otherwise do. If you don't escape the , vi thinks you just pressed and tries to execute the unfinished command.

  • See the section on grep in Chapter 6 for information about searching with regular expressions.

  • Add a g at the end of the command to make it apply to all occurrences in the file. Otherwise, it applies only to the first occurrence on each line.





Unix(c) Visual Quickstart Guide
UNIX, Third Edition
ISBN: 0321442458
EAN: 2147483647
Year: 2006
Pages: 251

Similar book on Amazon

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