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

How do I restrict a Vim search to match only within a specific range of line numbers?

Answer

/\%>5l\%<10l pattern

Explanation

Vim's \%>{lnum}l and \%<{lnum}l regex atoms act as zero-width line-number anchors inside a search pattern. By combining them, you can restrict any search — including n/N navigation — to match only within a specific range of lines, without limiting the search to a :s command range.

How it works

  • \%>5l — matches only at positions after line 5 (i.e., line 6 and beyond)
  • \%<10l — matches only at positions before line 10 (i.e., line 9 and earlier)
  • Combined: \%>5l\%<10l pattern finds pattern only on lines 6–9
  • The anchors apply to the pattern engine itself, so n and N will only cycle through matches inside that range

Example

To highlight and navigate occurrences of TODO only between lines 20 and 50:

/\%>19l\%<51l TODO

Every n keystroke jumps to the next TODO strictly within lines 20–50. Pressing n past line 50 produces "search hit BOTTOM" and wraps back to line 20.

To substitute within the same range without a command range:

:%s/\%>19l\%<51l TODO/DONE/g

Tips

  • Use \%{lnum}l (without > or <) to match exactly on one line
  • Column variants exist too: \%>5c (after column 5), \%<10c (before column 10)
  • Combine with \%V to further restrict matches to the last visual selection
  • These anchors work in any pattern context: :g//, :s//, n/N, and :vimgrep

Next

How do I use capture groups in Vim substitutions to rearrange or swap matched text?