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

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

Answer

/%>5l%<20lpattern

Explanation

Vim's \%>Nl and \%<Nl atoms restrict matches to lines after or before a given line number. Combining them constrains the search to a specific line range, leaving the rest of the file unhighlighted.

Atoms

Atom Matches when...
\%>Nl current line number is greater than N
\%<Nl current line number is less than N
\%Nl current line is exactly line N

Examples

Search for TODO only between lines 10 and 50:

/\%>10l\%<50lTODO

Substitute only within lines 20–30:

:%s/\%>20l\%<30lfoo/bar/g

Highlight only matches in the first 5 lines:

/\%<6lpattern

Combined with other atoms

Restrict to a column range too — only between columns 5 and 40:

/\%>5c\%<40cpattern

Tips

  • The line range is exclusive: \%>10l\%<20l matches lines 11–19, not 10 or 20
  • This is different from specifying a range in :s/{range}s/ — line atoms work inside the pattern itself
  • Combine with \%V (visual area) for even more precise targeting
  • :help /\%l documents all column, line, and byte position atoms

Next

How do I run a search and replace only within a visually selected region?