To search for a string in your text, you can use the forward slash (/) and question mark keys (?).
To search from your current position forward in the file, use the / key. For example to search for the word "apples" from the current cursor position to the end of the file, enter /apples and press Enter in command mode.
To search backward, to the start of the file, use the ? key. To search for "apples" from the current cursor position to the start of the file, enter ?apples and press Enter in command mode.
If you are looking for more than one occurrence of the word "apples" in the text, press the n key to move to the next occurrence.
r ■ rj As we discussed, Shift+g and g+g can be used in less and man to move to the
-■.■v..■¿•CV-.wend and start of a file. The /, ?, and n commands can also be used in these applications to search forward and backward in a file.
Replacing text globally in a file is quite easy to do and is very powerful, if you know what you are doing. To replace text in the whole document, you need to use the substitution command, :s.
For example, to replace the word "apples" with "pears" in the current document, enter :%s/apples/pears/g.
The :%s command is quite powerful in its ability to search and replace. In the example command, we used % to tell vim to check every line of the document for the occurrence of "apples". Adding the g tells it to replace all occurrences of "apples" on a line with "pears".
If you are worried that you could be replacing text you do not want to replace, you can add the c command onto the g to get vim to ask for confirmation.
This may seem to be quite a big step from some of the single commands we have talked about in this chapter so far, but we want to highlight how powerful vim can be with more abstract commands.
A good introduction to vim is included in the package; to run it, type vimtutor at the command line. If you want to access the online help, go into command mode and enter :h and press Enter. To exit the online help, enter :q in command mode and press Enter.
Was this article helpful?