Searching and Replacing
within VI



The following commands are performed in command mode.
To enter command mode, press the Esc key.


There are many ways to search through a file with vi.
I am not going to get to heavy into regular expressions in this document, but will give
the general syntax and some examples of searches I use often.



How to search for a pattern.

Search forward in the file for pattern.
    / pattern
Search backwards in the file for pattern.
    ? pattern
To get the next occurrence of pattern.
    n
To get the next occurrence of pattern in reverse direction.
    N


Special addressing symbols.

Current line.
    .
Last line of file or (end of line depending on how it is used).
    $
Entire file or (current file depending on how it is used).
    %
Beginning of the line.
    ^
Escape character.
    \
Alternate search delimiter.
    -


How to search and replace using ex commands.



Search the entire file (global search) and replace pattern1 with pattern2.
    :1,$s/pattern1/pattern2/g
or
    :%s/pattern1/pattern2/g
NOTE: The above will replace all occurrences of the pattern in the file!
MAKE SURE THIS IS WHAT YOU WANT!
If pattern1 is the word the every occurrence of the will be replaced including
there, them, they, etc. To replace just the word the see below.



Search the entire file (global search) and replace only the word pattern1 with pattern2.
    :1,$s/\<pattern1\>/pattern2/g
or
    :%s/\<pattern1\>/pattern2/g



To search for text that includes at / (forward slash), you can either \ (backslash)
escape the forward slash or change the delimiters.
    :%s/\/u\/test/\/u\/home/g
or
    :%s-/u/test-/u/home-g



You can use MARKED text or LINE numbers to refer to a block of text,
your search and replace will take place in the area of text you have referenced instead of the
whole file.

    :'a,'bs/pattern1/pattern2/g
or
    :100,200s/pattern1/pattern2/g