Search for next word (forward search)
To search in vim, open up your file with vim vim myfile.txt, and press ESC to switch to normal mode. Type / followed by the word you are searching for. For example, if we want to search for ‘ERROR’ in our file. We type /ERROR. This will take us to the first occurrence of the word.
To find the next occurrence, simply type n. And to go back to the previous occurrence, type N. To stop searching press ESC to go normal mode.
Search for previous word (backwards search)
To search backwards in a file, open up the file, vim myfile.txt, and press ESC to switch to normal mode. Type ? followed by the word. If we are searching for the word ‘INFO’ backwards, we type ?INFO. Type N to search backwards and n to search forwards. To stop searching press ESC to go normal mode.
Find current word
It is possible to find the current word the cursor is currently on. Open up a file in normal mode. Put the cursor on a word, then press * to find the next occurrence and # for the previous occurrence. On the bottom left corner, we can see the word that is being searched.
Case insensitive search
To ignore the case whilst searching, type / followed by a word, followed by \c. Let’s go through some examples, /Linux is case sensitive, /Linux\C is case sensitive, /Linux\c is case insensitive. It is also possible to set case sensitive search off in your vim config or the current file, by running :set ignorecase in normal mode.
Highlight search
To highlight search matches, set the hlsearch option by running :set hlsearch in normal mode or inside ~/.vimrc. Now try searching for a word and it will be highlighted everywhere in the file. To clear search highlighting, run :set nohlsearch in normal mode.
Search for any line starting with a word
Starting with ‘def’: /^def
Search for any line ending with a word
Ending with ‘return': /return$
Escaping special characters
Find ‘[0]’: /\[0\]
Find tabs in file
Use /^], to insert the “tab” character, do not type ^], rather after typing / press the tab key.
Written by
Neeran Gul
Staff Site Reliability Engineer, Mozn
Filed Under
Related Articles
Vim Find And Replace
You can use either the substitute command or the slash and dot method to search for patterns and replace with different values.
Vim Modes
Learn about seven of Vim’s modes
Vim / Vi Page Up and Down Controls
Quick reference for Vim's page up and down controls
Copy & Paste in Vim / Vi
Copy (Yank), Paste (Put) and Cut (Delete) in Vim
Undo & Redo in Vim / Vi
Keyboard shortcuts and summary of how Vim tracks changes
Show & Hide Line Numbers in Vim / Vi
Toggle absolute and relative line numbers
Select all in Vim / Vi
Select all and copy, paste, or delete the contents
Go To End of File in Vim / Vi
Select and delete to the end of a file in Vim
How to delete lines in Vim / Vi
The best answer depends on which mode you use