brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: :%s/pattern//gn counts matches in Vim without changing anything

Vim
~/tips/tip-vim-substitute-n-count-matches

:%s/error//gn

Counts how many times a pattern appears in the file, using the substitute command's n flag.

I often want to know how many times something appears in a file before I decide what to do with it. Vim can count it with the substitute command, without replacing anything.

The n flag of :substitute reports the number of matches and does not actually substitute. The Vim help says the matches are reported as if the 'report' option is zero, and that this is useful for counting items. Put it behind the usual g flag:

:%s/error//gn

Vim shows a message with the number of matches and the number of lines they are on. The file is not changed and the replacement text is empty, so there is nothing to undo.

The g flag matters. Without it, the help says, replacement occurs only for the first occurrence in each line, and that is how the counting works too. So :%s/error//n counts lines that contain the word, while :%s/error//gn counts every occurrence. Both are useful, I just need to know which one I am asking for.

A second trick from the help: if the pattern is empty, the command uses the pattern of the last substitute or :global, and if there is none, the previous search pattern. So after a search, I can count its matches without typing the pattern again:

/TODO
:%s///gn

That is the caveat as well. If you ran a substitute earlier in the same session, the empty pattern means that one and not your latest search. Check the message: if the number looks odd, type the pattern out in full.

You can limit the range, too. :'<,'>s/foo//gn counts inside a visual selection, which Vim fills in when you type : after selecting lines.

Further reading: Vim help: change.txt (:s flags)

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Vim tips :%s/<Ctrl-r><Ctrl-w>/newname/g /oldname find . -name "*.conf" | vim – vim --clean file.txt :set textwidth=72 All Vim tips (45) All topics

Link