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

How do I search for a pattern only within specific columns of a line?

Answer

/\%>10c\%<20cpattern

Explanation

When working with columnar data like CSV files, log files, or fixed-width records, you often need to match a pattern only when it appears in a specific column range. Vim's column atoms \%>Nc and \%<Nc let you restrict a search to a precise horizontal slice of each line.

How it works

  • \%>10c means "match only after column 10" (exclusive)
  • \%<20c means "match only before column 20" (exclusive)
  • Combined, they restrict the match to columns 11 through 19
  • c stands for column; use v for virtual columns (respects tabs)

The full search /\%>10c\%<20cpattern will only highlight and jump to occurrences of pattern that fall within columns 11-19.

Example

Given a log file:

2024-01-15 INFO  Server started on port 8080
2024-01-15 ERROR Connection refused to port 443
2024-01-15 INFO  Request processed on port 3000

Searching /\%>11c\%<17c\u\+ matches only the log level field (columns 12-16: INFO, ERROR), ignoring uppercase text elsewhere in the line.

Tips

  • Use \%Nc (without > or <) to match only at exactly column N
  • Combine with :g for powerful columnar filtering: :g/\%>11c\%<17cERROR/p prints only error lines
  • For virtual columns (which count tab stops as spaces), use \%v instead of \%c
  • Works with substitution too: :%s/\%>10c\%<20cold/new/g

Next

How do I ignore whitespace changes when using Vim's diff mode?