How do I search backward in Vim?
Answer
?pattern
Explanation
The ?pattern command searches backward through the file for the given pattern, starting from the cursor position and wrapping around to the end of the file if no match is found before the beginning.
How it works
- Press
?to enter backward search mode — the cursor moves to the command line with a?prompt - Type your search pattern and press
<CR>(Enter) - Vim moves the cursor to the nearest match above the current position
- Press
Nto continue searching backward (same direction) ornto search forward (opposite direction)
Example
Given the text with the cursor on the last line:
The quick brown fox
jumps over the lazy dog
the end of the story
Typing ?the<CR> moves the cursor backward to the on the second line. Pressing N jumps to The on the first line (if ignorecase is set).
Tips
- Use
/patternto search forward instead — the counterpart to? - After a
?search,ngoes backward (same direction) andNgoes forward (opposite direction) — this is reversed compared to/searches - Use
?\<word\>to match whole words only - Use
?\Cpatternto force a case-sensitive search - Use
?\cpatternto force a case-insensitive search - Press
?<CR>(with no pattern) to repeat the last backward search - Use
:set hlsearchto highlight all matches in the file - Press
#as a shortcut to search backward for the word under the cursor