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

How do I search for a pattern only on a specific line number or at a specific column position?

Answer

\%l and \%c

Explanation

Vim's \%l and \%c pattern atoms anchor a search to a particular line number or column, enabling surgical searches and substitutions that standard regex cannot express.

How it works

These atoms are used inside any Vim search pattern or :s command:

  • \%42l — matches only on line 42
  • \%10c — matches only at byte column 10
  • \%10v — matches only at virtual column 10 (respects tabstop — usually preferable)
  • \%>42l / \%<42l — match after / before line 42
  • \%>80v / \%<80v — match after / before virtual column 80

Combine them freely with any other pattern atoms.

Example

Delete a stray semicolon only on line 5:

:5s/;$//

Highlight all characters beyond column 80 (great for spotting long lines):

/\%>80v./

Substitute TODO only between lines 10 and 20 using line anchors instead of a range:

:%s/\%>9l\%<21lTODO/FIXME/g

Remove the first character of line 3 only:

:3s/\%3l^.//

Tips

  • Prefer \%v (virtual column) over \%c (byte column) when working with tabs or multi-byte characters
  • These atoms make :global plus line anchors redundant for many cases — a single :s with \%l is cleaner
  • Visual column highlighting beyond 80 chars: set match OverLength /\%>80v.\+/ in your vimrc for a persistent indicator

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?