Search and Replace – Using vi Editor


Search and Replace

To substitute pattern 1 with pattern 2 on the line your cursor is on, use the :s/pattern1 /pattern2 command. The s stands for substitute; pattern1 is the pattern to search for and will be replaced; pattern2 is the pattern that will replace pattern1.

Search and Substitute for a Range

To search for a pattern over a range of lines and replace it with a substitute pattern, use the :line number1,line number2  s /pattern1/pattern2 command. Let’s examine what this command does in the following example,

:5,25s/January/01. For lines 5 through 25, substitute 01 for January. If there is more than one occurrence of pattern 1 on a line, only the first occurrence will be replaced.

Global Search and Replace

To search for all occurrence of pattern 1 on all lines in the file, use the  :1,$s/pattern1/pattern2/g command. This will search from line 1 to the end of the file (represented by the $) for pattern  1 and replace it with pattern2. The g at the end of the command stands for global, and means to replace every occurrence of pattern 1, including more than one occurrence per line.

Interactive Search and Replace 

Add the option c to the end of the global search and replace to make it interactive. You’ll be prompted for a yes or no response when replacing the occurrence of pattern. At the bottom of the screen, you’ll be prompted to reply Y or n for each replacement. The default, or just pressing [Enter] ,is the same as entering n.


Searching and Replacing Text

Objective:  To locate a pattern in the file and replace it with another pattern.

  1. Enter /Carlson to move to one of the Carlson entries.
  2. Enter :s/Carlson/Hanson to replace Carlson with Hanson. Notice that this made the replacement only on the current line.
  3. Enter  :1,$s/Carlson/Hanson to replace Carlson with Hanson through-out the file.
  4. Search for Carlson.

             Did you find any entries containing this pattern? If so, why?

  Yes, because the basic search and replace substitution replaces only one pattern per line. (You can tell this was originally Carlson Mfg. because it is now Hanson Mfg.)

       5.       Undo the last change.

       6.        Now, let’s do a global, interactive substitution. Add /gc to the previous command (:1, $s/Carlson/Hanson/gc). Answer y to all prompts for replacement except for the replacement of Carlson Lane (so you’ll only be changing Carlson Mfg. entries).

       7.  Search for Carlson Mfg. to verify that all Carlson Mfg. entries have been changed to Hanson Mfg.

       8. Save the changes as salesupdate by entering  :wq  salesupdate. Verify that sales and salesupdate both exist with different time and date stamps (ls  –l  sales  salesupdate). 


About Author


Leave A Reply

CAPTCHA ImageChange Image