Thursday, April 28, 2011

Search for string and get count in VI editor

Well I want to search for a string and find number of occurrences in a file opened using Vi editor.

From stackoverflow
  • :%s/string/string/g will give the answer.

    ojblass : What a better answer. +5 if possible
  • 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.

    kadeshpa : It looks like this answer is for Vim users and not for Vi :(
    dirkgently : Do you only have vi on your system? Which version?
    ojblass : Someone tagged your quesiton with vim in it... I removed it.
  • :g/xxxx/d

    This will delete all the lines with pattern, and report how many deleted. Undo to get them back after.

    ldigas : Of course, he can just omit the "d" so he doesn't have to unto the operation.
    anon : Note this only tells you how many lines - not how many occurences. I think dirk's is a better solution.
    Mohit Chakraborty : My solution below correctly counts multiple occurences within a line and there is nothing to undo.
  • THE way is

    :%s/pattern//gn

0 comments:

Post a Comment