Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

Searching and Replacing in vi

One of vi’s better features (and advantages over nano) 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 red_a.jpg), or you can find the text and replace it with other text, as in red_b.jpg.

086fig01.jpg

Click to view larger image

red_a.jpg Searching for text in vi is quick and reliable.

086fig02.jpg

Click to view larger image

red_b.jpg 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. esc.jpg/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. enter.jpg

    Press enter.jpg to find the first occurrence of the term. Type n.jpg to find the next one.

To search and replace in vi:

  1. vi hairyspider

    For starters, access vi and a specific file.

  2. esc.jpg:%s/spider/horrible horrible awful spider/

    Enter esc.jpg:%s/ plus the text to find, another /, followed by the replacement text, as in gray_b.jpg. Here, we replace “swallowed a fly” with “swallowed a spider to catch the fly,” but perhaps you might forgo the spider and simply go for some antacid.

  • + Share This
  • 🔖 Save To Your Account