Scrolling through a long file to find one line is slow. In Vim you search instead. All the commands here start in Normal mode, so press Esc first.
Searching forwards and backwards
Type /, then the pattern, then Enter:
/errorThe cursor jumps to the next match after its position. Use ? to search backwards:
?errorRepeating a search
nrepeats the search in the same direction.Nrepeats it in the opposite direction.
After ?error, "same direction" means backwards, so n moves up the file.
By default, full Vim wraps around at the end of the file and shows:
search hit BOTTOM, continuing at TOPIf nothing matches, you see a message such as E486: Pattern not found: eror. The wrapscan option controls wrapping.
Searching for the word under the cursor
Put the cursor on a word and press * to find its next occurrence, or # to find the previous one. These match the whole word, so * on log skips login.
You can ask for whole words yourself with \< and \>:
/\<log\>Patterns are regular expressions
Vim searches use regular expressions. ^ is the start of a line, $ the end, . any character, and * zero or more of the previous item.
/^Port
/;$Vim's default syntax differs from grep -E. Write \+ for "one or more" and \| for "or". To find a literal dot, write \..
/192\.168\.
/warn\|errorUpper and lower case
Searches normally care about case. These settings change that:
:set ignorecase
:set smartcaseWith both on, /error also finds Error, but /Error matches only that capitalisation, because you typed a capital. For a single search, add \c to ignore case or \C to respect it, as in /error\c.
Highlighting
:set hlsearch highlights all matches. When the highlight gets in the way, :nohlsearch (short form :noh) clears it until the next search. Some minimal vi builds do not support every option shown here.
Try it
- Copy a text file to practise on:
cp /etc/services ~/services.txt. If your system lacks it, use any long file. - Open the copy with
vim ~/services.txt. - Search with
/tcp, then pressna few times andNonce. - Move onto a word and press
*. - Try
/^ssh, then turn on:set ignorecaseand search again. - Quit with
:q!.
For a live shell to practise in, there is the search and archives lab.
Check your understanding
Vim Search Patterns
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.