vimtricks.wiki Concise Vim tricks, one at a time.

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

  • \%>10l matches only after line 10
  • \%<20l matches only before line 20
  • Combined: \%>10l\%<20lpattern matches pattern only 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 \%l are 1-based
  • Use \%23l (exact match) for a single-line restriction
  • These atoms work in both / search and :s substitution
  • Combine with visual selection: \%V restricts to the visual area, \%l to line ranges
  • Documented under :help /\%l

Next

How do I run the same command across all windows, buffers, or tabs?