Searching & Replacing Text

vi has a number of search commands. You can search for individual characters through to regular expressions.

The main two character based search commands are f and t.

fc: Find the next character c. Moves RIGHT to the next.
Fc: Find the next character c. Moves LEFT to the preceding.
tc: Move RIGHT to character before the next c.
Tc: Move LEFT to the character following the preceding c.

If the character you were searching for was not found, vi will beep or give some other sort of signal.

vi allows you to search for a string in the edit buffer.

/str: Searches Right and Down for the next occurance of str.
?str : Searches Left and UP for the next occurance of str.
n: Repeat the last / or ? command
N: Repeats the last / or ? in the Reverse direction.

When using the / or ? commands a line will be cleared along the bottom of the screen. You enter the search string followed by RETURN.

The search and replace command allows regular expression to be used over a range of lines and replace the matching string. The user can ask for confirmation before the substitution is performed. It may be well worth a review of line number representation in the ed tutorial.

:<start>,<finish>s/<find>/<replace>/g General command
:1,$s/the/The/g Search the entire file and replace the with The.
:%s/the/The/g% means the complete file. (Same as above).
:.,5s/^.*//g Delete the contents from the current to 5th line.

The search command is very powerful when combined with the regular expression search strings. If the g directive is not included then the change is performed only on the first occurrence of a match on each line.

Supported By

File Browser Reference
Department FHERIS
University of Galway
HEA Logo