Search string and count in vi editor

I want to find a string and find the number of occurrences in a file using the vi editor.

+84
search vi count
Apr 3 '09 at 20:37
source share
7 answers
:g/xxxx/d 

This will delete all lines with the pattern and tell you how many are deleted. Cancel to return them after.

+17
Apr 03 '09 at 20:43
source share

Way

:% s / pattern // dp

+127
Oct 13 '10 at 18:20
source share

You need flag n . To count words use:

 :%s/\i\+/&/gn 

and specific word:

 :%s/the/&/gn 

See the count-items section.

If you just enter:

 %s/pattern/pattern/g 

then the status bar will also give you the number of matches in vi.

+118
Apr 03 '09 at 20:42
source share

:% s / line / line / g will give an answer.

+36
Apr 03 '09 at 20:41
source share

(similar to Gustavo, but additionally :)

For any previous search, you can simply:

 :%s///gn 

The template is not needed because it is already in the search register ( @/ ).

"%" - make s/ in the whole file
"g" - global search (with several hits in one line)
"n" - prevents any replacement s/ - nothing is deleted! nothing should be undone!
(see :help s_flag for more information)

(Thus, it works great with β€œSearch for visually selected text,” as described in vim-wikia tip171 )

+17
Aug 28 '13 at 12:02
source share

use

:% s / pattern / \ 0 / g

when the pattern string is too long and you don't like typing it again.

+2
Feb 18 '11 at 2:27
source share

I suggest doing:

  • Search for either * to do a "limited 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 entries.

** I really could find a plug-in that would send a message "matching N from N 1 to N 2 rows" with every search, but alas.

Note: Do not confuse the complex wording of the output. The first command can give you something like 4 matches on 3 lines , where the last can give you 3 matches on 3 lines . While technically accurate, the latter is misleading and must say that "3 lines correspond." So, as you can see, you never need to use the last form (only "n"). You get the same information more clearly and more using the "gn" form.

0
Jan 11 '17 at 17:12
source share



All Articles