Count the number of occurrences of a string using sed?

前端 未结 6 1852
星月不相逢
星月不相逢 2020-12-28 17:18

I have a file which contains \"title\" written in it many times. How can I find the number of times \"title\" is written in that file using the sed command provided that \"t

6条回答
  •  借酒劲吻你
    2020-12-28 17:32

    Revised answer

    Succinctly, you can't - sed is not the correct tool for the job (it cannot count).

    sed -n '/^title/p' file | grep -c
    

    This looks for lines starting title and prints them, feeding the output into grep to count them. Or, equivalently:

    grep -c '^title' file
    

    Original answer - before the question was edited

    Succinctly, you can't - it is not the correct tool for the job.

    grep -c title file
    
    sed -n /title/p file | wc -l
    

    The second uses sed as a surrogate for grep and sends the output to 'wc' to count lines. Both count the number of lines containing 'title', rather than the number of occurrences of title. You could fix that with something like:

    cat file |
    tr ' ' '\n' |
    grep -c title
    

    The 'tr' command converts blanks into newlines, thus putting each space separated word on its own line, and therefore grep only gets to count lines containing the word title. That works unless you have sequences such as 'title-entitlement' where there's no space separating the two occurrences of title.

提交回复
热议问题