问题
I want to search for a string and find the number of occurrences in a file using the vi editor.
回答1:
:g/xxxx/d
This will delete all the lines with pattern, and report how many deleted. Undo to get them back after.
回答2:
THE way is
:%s/pattern//gn
回答3:
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.
回答4:
:%s/string/string/g will give the answer.
回答5:
(similar as Gustavo said, but additionally: )
For any previously search, you can do simply:
:%s///gn
A pattern is not needed, because it is already in the search-register (@/
).
"%" - do s/
in the whole file
"g" - search global (with multiple hits in one line)
"n" - prevents any replacement of s/
-- nothing is deleted! nothing must be undone!
(see: :help s_flag
for more informations)
(This way, it works perfectly with "Search for visually selected text", as described in vim-wikia tip171)
回答6:
use
:%s/pattern/\0/g
when pattern string is too long and you don't like to type it all again.
回答7:
I suggest doing:
- Search either with
*
to do a "bounded search" for what's under the cursor, or do a standard/pattern
search. - Use
:%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.
来源:https://stackoverflow.com/questions/715643/search-for-string-and-get-count-in-vi-editor