Vi Search and Replace

Search and Replace

To begin a search and replace in Vi or Vim, start by hitting the colon <:>. This will allow you to enter a Vi command. Then, enter a search and replace command like so:


This will search every line for ‘old’ and replace all occurrences in the line with ‘new’. You start by mentioning which lines to affect. In my example, I use ‘%s’. This translates to all lines. Then, I trail the command with ‘g’ (for global) to affect all occurrences in the lines defined by ‘%s’. Note that global does not mean the entire file!

Limiting the Replace

You can declare the search and replace for only the current line by removing the percent sign:


It is also possible to limit the affected line numbers. The next example only affects lines 40 through 42:

40,42 s/old/new/g

Eliminating the ‘g’ from the end will only replace the first occurrence per line defined in the search. For example, the following replaces the first instance of ‘hello’ on every line in the file:

Regular Expressions

The search string can be the form of a regular expression. In the next example, I replace all numbers with the word ‘number’.


Escaping Characters

You will have to escape out the slash </> if it is part of your search string:


Use Any Delimiter

Alternatively, change your delimiter. It can be anything!


Get Confirmation Before Changing

You can get confirmation for each replace by adding a ‘c’ to the end of your command:

For more information, see the online Vi documentation.