Search and Replace in Vi/Vim

vim.png

In Vi or Vim, use the forward slash </> to search. Then type in your search string and hit <Enter>. You can navigate through occurrences of your search string using <n> to move forward and <N> to move backwards.

If you do not want Vim to highlight searches, set the following in your ~/.vimrc

set nohlsearch

To wrap searches around the file when using <n> and <N>, set the following in your ~/.vimrc

set wrapscan

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.

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:

%s/old/new/gc

Sources 1 , 2

Related Posts

Comments are closed.