Searching and Replacing
Searching a document for a given string or character to replace it is commonly performed either in vi while editing a given file or by the sed command on a large set of data. Both vi and the sed command share a common search-and-replace syntax, with small differences that won't confuse you if you use both. Indeed, learning to search and replace in one will teach you how to use it in the other.
The search-and-replace syntax is as follows:
action/tofind/replacewith/modifier
For example, the following string in vi replaces just the first instance of the string bob in the current line with the string BOB:
:s/bob/BOB/
To replace all instances of the string bob with BOB in the current line, you would use this line:
:s/bob/BOB/g
The g stands for global or doing the action on every found instance of the string.
To replace all instances of bob with BOB in the entire file, no matter how many exist or how many changes are made to each line, you would use this:
:%s/bob/BOB/g
CAUTION
It's critical that you read the exam question and all its answers (except for a fill-in-the-blank) to see exactly what is being asked for. A percent symbol (%) in front of the search-and-replace string is the only way to cause vi to search the entire file, and not just the current line.
Fuzzy Searches
Finding matches for fuzzy searches in vi is a good thing to know about. In a fuzzy search, you find something you only know a part of.
For example, if you wanted to find all the instances of the word The at the beginning of a line, you could use this search:
/^The
To find all the instances of the word kernel at the end of a line, you could use this search:
/kernel$
In some instances, you'll need to find what's called a metacharacter. For example, say you wanted to find the instances in a file of the asterisk (*) character because it stands for many characters. You could use something like this:
/The \* character
Another example might be finding the text kernel., with the period being treated only as a period. Otherwise, you'd find kernels, kernel?, kernel!, and so on. To find just kernel., you'd use the following:
/kernel\.
Finally, matching a range of characters is helpful, such as trying to find all instances of the version number string v2.1 through v2.9. You either have to perform several searches or use something like this:
/v2.[1-9]
The square brackets denote a single character, stretching from the first character to the one after the dash. If you wanted instead to find all versions of the word the, including THE, THe, and tHE, you would use the following:
/[tT][hH][eE]