How do I restrict a search to only match within a specific line range?
Answer
/\%>10l\%<20lpattern
Explanation
Vim's \%>Nl and \%<Nl atoms restrict a search pattern to match only between specific line numbers. This lets you search within a precise region of your file without affecting the rest.
How it works
\%>10lmatches only after line 10\%<20lmatches only before line 20- Combined:
\%>10l\%<20lpatternmatchespatternonly on lines 11-19
Examples
" Search for 'TODO' only between lines 50 and 100
/\%>49l\%<101lTODO
" Search for 'error' only in the first 20 lines
/\%<21lerror
" Search for 'return' only after line 100
/\%>100lreturn
Column restrictions
You can also restrict by column:
" Match 'pattern' only in column 1-40
/\%<41cpattern
" Match only in column 80+ (long lines)
/\%>79c.
Practical uses
- Search within a specific function without selecting it first
- Find patterns only in the header section of a file
- Use in substitutions:
:%s/\%>10l\%<20lold/new/g - Combine with column restrictions for precise region targeting
Tips
- Line numbers in
\%lare 1-based - Use
\%23l(exact match) for a single-line restriction - These atoms work in both
/search and:ssubstitution - Combine with visual selection:
\%Vrestricts to the visual area,\%lto line ranges - Documented under
:help /\%l