Wednesday, February 4, 2009

Vi Search and Replace

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:

%s/old/new/g

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:

s/old/new/g

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'.

%s/[0-9]/number/g

Escaping Characters

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

%s/http:\/\//https:\/\//g

Use Any Delimiter

Alternatively, change your delimiter. It can be anything!

%s!http://!https://!g

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.

No comments: