Categories
Server

How to use Vim for Global Text Replacement

If you’re working in Vim, one of the most powerful text editors, you might often need to replace multiple instances of a string throughout a file. Vim offers a handy way to perform global text substitutions with the following command:

%s/old-text/new-text/g

What Does This Command Do?

  • :: Enters command mode in Vim, allowing you to execute commands.
  • %: Refers to the entire file. It tells Vim to search through all lines of the file. Without %, Vim would only search the current line.
  • s: Stands for “substitute,” which is Vim’s command for search and replace.
  • old-text: The text string you want to search for and replace.
  • new-text: The text string you want to use as the replacement.
  • g: This flag stands for “global,” meaning Vim will replace all instances of old-text on each line. Without the g flag, only the first occurrence on each line would be replaced.

Example Use Case

Suppose you have a file with many occurrences of the word “apple” and want to change them all to “orange.” You would run:

%s/apple/orange/g

This command will go through the entire file and replace every occurrence of “apple” with “orange.”