I want to search for a string and find the number of occurrences in a file using the vi editor.
I suggest doing:
*
to do a "bounded search" for what's under the cursor, or do a standard /pattern
search.:%s///gn
to get the number of occurrences. Or you can use :%s///n
to get the number of lines with occurrences.** I really with I could find a plug-in that would giving messaging of "match N of N1 on N2 lines" with every search, but alas.
Note:
Don't be confused by the tricky wording of the output. The former command might give you something like 4 matches on 3 lines
where the latter might give you 3 matches on 3 lines
. While technically accurate, the latter is misleading and should say '3 lines match'. So, as you can see, there really is never any need to use the latter ('n' only) form. You get the same info, more clearly, and more by using the 'gn' form.
You need the n
flag. To count words use:
:%s/\i\+/&/gn
and a particular word:
:%s/the/&/gn
See count-items documentation section.
If you simply type in:
%s/pattern/pattern/g
then the status line will give you the number of matches in vi as well.