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

How do I count the number of lines containing a pattern without making any replacements?

Answer

:%s/pattern//n

Explanation

The n flag in the substitute command suppresses the actual replacement and instead reports the match count. Without the g (global) flag, Vim counts one match per line, giving you the number of lines that contain the pattern — similar to grep -c.

How it works

  • % — apply to the entire file
  • s/pattern// — the substitution (source pattern, empty replacement)
  • n — do not substitute; just report the count

Without g, Vim counts only the first occurrence per line. This means the output tells you how many lines match, not how many total occurrences there are.

For total occurrences across all lines, use gn instead: :%s/pattern//gn

Example

Suppose your file has:

foo bar foo
baz
foo

Running :%s/foo//n reports:

2 matches on 2 lines

Running :%s/foo//gn reports:

3 matches on 2 lines

The first form (without g) counts matching lines; the second counts all occurrences.

Tips

  • Combine with a range to count matches in a section: :10,50s/TODO//n
  • Use \c for case-insensitive counting: :%s/\cfoo//n
  • The n flag works with any search pattern, including multiline patterns with \n
  • This is non-destructive: the buffer is never modified

Next

How do I change the working directory to the folder containing the current file without affecting other windows?