How to grep number of unique occurrences

前端 未结 3 1589
鱼传尺愫
鱼传尺愫 2021-01-12 09:12

I understand that grep -c string can be used to count the occurrences of a given string. What I would like to do is count the number of unique occurrences when

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 09:52

    In general, if you want to grep and also keep track of results, it is best to use awk since it performs such things in a clear manner with a very simple syntax.

    So for your given file I would use:

    $ awk -F= '/string=/ {count[$2]++} END {for (i in count) print i, count[i]}' file
    value1 3
    value2 2
    value3 1
    

    What is this doing?

    • -F=
      set the field separator to =, so that we can compute the right and left part of it.
    • /string=/ {count[$2]++}
      when the pattern "string=" is found, check it! This uses an array count[] to keep track on the times the second field has appeared so far.
    • END {for (i in count) print i, count[i]}
      at the end, loop through the results and print them.

提交回复
热议问题