How to Search in Vim / Vi

Posted 

3 min read

This article describes how to perform search operations in Vim / Vi.

Vim or its precursor Vi comes preinstalled on macOS and most Linux distributions. Searching text is one of the most common tasks when working with files. Knowing the basics of Vim might be very useful when you encounter a situation where your favorite editor is not available.

To search in Vim you must be in normal mode. When you launch the Vim editor, you’re in this mode. To go back to normal mode from any other mode, just press the Esc key.

Vim allows you to quickly find text using the / (forward slash) and ? (question mark) commands.

To search forwards press / and to search backward press ?, type the search pattern and press Enter to run the search:

It is important to note that the search command looks for the pattern as a string, not a whole word. If for example, you were searching for “gnu”, the search find matches where “gnu” is embedded in larger words, such as “cygnus” or “magnum”.

Press n to search for the next occurrence or uppercase N to search the opposite direction.

The basic steps to perform a search in Vim are as follows:

  1. Press /.
  2. Type the search pattern.
  3. Press Enter to perform the search.
  4. Press n to find the next occurrence or N to find the previous occurrence.

Search for Whole Word

To search for a whole word, start the search by pressing / or ?, type \< to mark the beginning of a word, enter the search pattern, type \> to mark the end of a word, and hit Enter to perform the search.

For example, to search for “gnu” you would use /\<work\>:

Search the Current Word

You can also search for a whole word by moving the cursor to the word and pressing * (asterisk) to search forwards or # (hash) to search backwards. To find the next match press * or # again.

Search History

Vim keeps track of all the search operations you made in the current session. To browse the search history press / or ? and use the arrow up/down keys to find a previous search operation. To run the search, simply press Enter. You can also edit the search pattern before performing the operation.

Case sensitivity

By default, the search result is case sensitive; searching for “GNU” will not match “Gnu”.

To ignore case type :set ignorecase or :set ic in the Vim command line. You can also set the ignore case to be a default optin by adding the command in your ~/.vimrc file.

To change back to case match mode, type :set noignorecase or :set noic.

Another way to force ignore case is to append \c after the search pattern. For example /Linux\c will perform ignore case search. Uppercase \C after the pattern forces case match search.

Conclusion

To search in Vim/Vi type / or ?, enter the search pattern and hit Enter.

Feel free to leave a comment if you have any questions.