Search for string and get count in vi editor

前端 未结 8 1785
小鲜肉
小鲜肉 2021-01-30 01:12

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

相关标签:
8条回答
  • 2021-01-30 01:42

    use

    :%s/pattern/\0/g

    when pattern string is too long and you don't like to type it all again.

    0 讨论(0)
  • 2021-01-30 01:44
    :g/xxxx/d
    

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

    0 讨论(0)
  • 2021-01-30 01:44

    :%s/string/string/g will give the answer.

    0 讨论(0)
  • 2021-01-30 01:44

    Short answer:

    :%s/string-to-be-searched//gn

    For learning:

    There are 3 modes in VI editor as below

    • : you are entering from Command to Command-line mode. Now, whatever you write after : is on CLI(Command Line Interface)
    • %s specifies all lines. Specifying the range as % means do substitution in the entire file. Syntax for all occurrences substitution is :%s/old-text/new-text/g
    • g specifies all occurrences in the line. With the g flag , you can make the whole line to be substituted. If this g flag is not used then only first occurrence in the line only will be substituted.
    • n specifies to output number of occurrences
    • //double slash represents omission of replacement text. Because we just want to find.

    Once got the number of occurrences, you can Press N Key to see occurrences one-by-one.

    For finding and counting in particular range of line number 1 to 10:

    :1,10s/hello//gn

    • Please note, % for whole file is repleaced by , separated line numbers.

    For finding and replacing in particular range of line number 1 to 10:

    :1,10s/helo/hello/gn

    0 讨论(0)
  • 2021-01-30 01:45

    THE way is

    :%s/pattern//gn

    0 讨论(0)
  • 2021-01-30 01:45

    (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)

    0 讨论(0)
提交回复
热议问题