Sometimes, we look for a particular text in a file. And, reading hundreds of lines wouldn't be the preferred choice in any manner. Apart from that, we also code comment our program files. So, if have got thousand lines of code, then searching the code manually isn't always the best option. Directly, just look for the code comments and we would get to the destination. This is only possible with search functionality. In this article, we would discuss how to search in a file with vim.
Although, numerous Graphical text editors can do the same. But, vim in particular is something which we can rely on all the time. It could be possible that some text editor won't be available on an operating system. But, vim or vi should be there.
Search in a file with vim
First, we need to see if we are searching for text forward or backward. If we are at the beginning of the file then, definitely we need to search the text forward. Otherwise, we if are at the end then, we would search backwards.
We have mentioned the above for a specific reason. In vim, we have got two special characters slash (/) and question mark (?).
So, if we are searching forward - we use slash (/). Otherwise, question mark (?) would do the job.
Let's see how its done. Open a file with vim -
It opens the file in command mode. Now, to look for a word use slash (/) and put the word which we are searching after it. For instance, if we search for a word - "are". Then, do - /are
And, press Enter. To search for subsequent occurrence of the word, use n (next) till the time the patterns start to repeat. Or, use b key to search for patterns backwards.
Similarly, we can use question mark (?) if we intend to search backwards. Continuing with the above example, ?are will look for the word "are" backwards.
It is worth mentioning here that, search in vim is case sensitive. So, if you are searching for both "are" and "Are". Then, use square brackets /[aA]re or ?[aA]re
To quit vim, use :q and Enter.
In conclusion, we have discussed how to search in a file with vim using slash (/) and question mark (?).
Additional Info -
Regex search with vim
Here, we would cover the basic example which uses regular expressions to look for pattern. If we looking for a line with characters - sys and ends with - md, then this is how we should put it.
. (dot) is used represent any character and * (asterisk) is for the any number of times. So, it will look for lines which have sys and ends with md. And, no matter how many characters are there in between. Rest all, like how to move forwards, backwards etc. we have already discussed above.