Search and Replace in vi

I frequently edit documents in vi and one task that’s often required is searching and replacing text. To search and replace text, you can use the substitute command :s, which follows the pattern :[range]s/{search-string}/{replacement-string}/[flags].

Example of range values:

  • % – indicates the search should occur with all lines
  • 4 – indicates the search should occur on line 4
  • 2,8 – indicates the search will occur from line 2 to line 8

Examples of flag values:

  • g – make the replacement if the text is found for all instances
  • c – ask for confirmation of a change
  • i – not case sensitive
  • I – case sensitive
  • e – don’t report error messages if no match is found

Usage examples:

Find and replace

:s/StringToFind/Replacement/

Find and replace all instances on the current line

:s/StringToFind/Replacement/g

Find and replace all instances from line 5 to line 7 upon confirmation

:5,7s/StringToFind/Replacement/gc

Find and replace with case sensitivity throughout the entire document

:%s/StringToFind/Replacement/gI

To learn more about the substitute command, open vi and type :help :s

Advertisements

Help in vi

Vi is a great text editor but requires practice to learn its many commands. To aid this process vi provides a great command called help. User’s can access an overview of the help command, by typing the following;

:help

For a listing of common commands used by vi, type;

:help quickref

For help with a specific command you can also type :help <command>. For example, to see the help for the insert command you would type;

:help i