3

This question already has an answer here:

I've extracted strings I'm interested in from another file and now have a list like this:

StringA
StringB
StringA
StringA
StringB
StringC
StringB

How can I extract the number of occurrences each string has using common command-line tools?

I would like to end up with a list like this:

StringA 3
StringB 3
StringC 1

marked as duplicate by Sergiy Kolodyazhnyy, slm Jul 5 '18 at 21:01

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    That is NOT json. – ctrl-alt-delor Jul 5 '18 at 13:45
  • @ctrl-alt-delor let me quote from above "and I've extracted strings I'm interested in" - I didn't say that the shown snippet is JSON! – stdcerr Jul 5 '18 at 13:52
  • 1
    So what am I supposed to do with that information. How is it relevant that it was JSON. May be it could be used to create a different answer, that processes the JSON, so yes put it at the end. But at the beginning, I have to parse that, and realise that it is not relevant. It just adds more effort for the reader. – ctrl-alt-delor Jul 5 '18 at 13:55
  • I was half-tempted to write a pure-Bash solution, but I think that's not what you want, so let's edit away the reference to that particular shell. – ilkkachu Jul 5 '18 at 13:58
8

Use:

sort file | uniq -c

Looks simple?

  • That's it! my extraction stuff |sort|uniq -c does the trick! Great, Thanks! – stdcerr Jul 5 '18 at 13:13
6

With GNU datamash:

datamash -s -g1 count 1 <file

The output:

StringA 3
StringB 3
StringC 1

Not the answer you're looking for? Browse other questions tagged or ask your own question.