Skip to content

Linux Foundations / Find your way around Linux ยท Step 50 of 63

Lesson: Vim Search PatternsSwitch
โ† Linux Foundations

Shell and files

Vim Search Patterns

Search forwards and backwards in Vim, repeat matches and control letter case.

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:

text
/error

The cursor jumps to the next match after its position. Use ? to search backwards:

text
?error

Repeating a search

  • n repeats the search in the same direction.
  • N repeats 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:

text
search hit BOTTOM, continuing at TOP

If 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 \>:

text
/\<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.

text
/^Port
/;$

Vim's default syntax differs from grep -E. Write \+ for "one or more" and \| for "or". To find a literal dot, write \..

text
/192\.168\.
/warn\|error

Upper and lower case

Searches normally care about case. These settings change that:

vim
:set ignorecase
:set smartcase

With 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

  1. Copy a text file to practise on: cp /etc/services ~/services.txt. If your system lacks it, use any long file.
  2. Open the copy with vim ~/services.txt.
  3. Search with /tcp, then press n a few times and N once.
  4. Move onto a word and press *.
  5. Try /^ssh, then turn on :set ignorecase and search again.
  6. 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.