Searching in Vim
Now, Vim provides various methods of searching but the default approach is that it searches for the first instance of the given string, whether it be a substring of a word or a word itself, and will highlight it. The syntax of searching is:
/<search word>
First, you need to open a document in Vim and then, enter command mode. After this, vim will switch to search mode and whatever you will type after ‘/’, vim will search its first occurrence in the document.
For example, we will open a dummy file and search geek in it. To do this, we need to type the following in command mode.
/geek
Output:
As we can see, that vim highlighted the first instance of ‘geek’ in the file. Now, we shall look on different ways of searching.
1) Using case insensitive searching
By default, vim uses case sensitive searching however, it provides a command to change this to case insensitive searching. The command is as follows
:set ignorecase
This, allows to change the search to case insensitive. To enter this command, you have to be in command mode and then type in the entire command given above.
For example, after changing this, if we now search for GeEk then, we will still get the same results as above.
/GeEk
Output:
Here, vim searches for the given string without accounting for the letter case.
Also, you can also turn back the case sensitive search by entering the following command in command mode.
:set ignorecase!
2) Exact word matching
Another method of searching in vim is to search the given word as a proper string and not a substring. For example, in previous examples, we searched for geek however, we got results even though it was part of the word w3wiki. This is the default setting in Vim for searching however, it can be changed by wrapping the word we search for inside the given characters
\< word >\
For example, we will search for the first string instance of is in the document. In the default mode, it should highlight the ‘is’ inside the ‘this’ word of the first line but, because of exact word matching, it will highlight the second word in first line.
/\<is\>
Output:
Vim
Searching and Replacing in Vim Editor
Vim is an excellent version of the legacy Vi editor for terminals. It is a complete command line-based text editor that has been the go-to choice for IT professionals for decades. Vim is the Vi-IMproved version of the original text editor which contains many modern features. In this article, we shall explore one such feature, the functionality to search and replace in a file. We will see various methods of searching and replacing based on different criteria such as letter case, regular expressions, etc.
Contact Us