I'm playing with bash pipelines using a bunch of NBA data. I'm trying to count the frequency of players on the Cleveland Cavaliers, and right now my command looks something like cut -d "," -f 2 nba2017-roster.csv | grep "CLE" | uniq -c. The output is 15 "CLE".

I want the 15, not the "CLE". How can I do this? Thanks!

  • 3
    What you are looking for is wc -l. uniq is an overkill. – pfnuesel Mar 19 '18 at 16:22
  • 2
    @pfnuesel, or just grep -c CLE here and neither uniq -c nor wc -l. – Stéphane Chazelas Mar 19 '18 at 16:24
  • @pfnuesel But that just gives me the number of lines, which is obviously 1 and not what I want? – Jake Mar 19 '18 at 16:25
  • @StéphaneChazelas exactly what I needed, thanks. – Jake Mar 19 '18 at 16:26

With UNIX, there's typically more than one way to do it.

Stéphane mentioned the most straight-forward method, which is to drop the uniq -c in favor of just counting with grep:

... | grep -c CLE

If you really want to keep the uniq -c portion of the command-line, then you either need to find a way to remove the "CLE" or keep just the number. The uniq utility is specified to return counts in the format:

"%d %s", <number of duplicates>, <line>

so one (of many) options to extract the <number of duplicates> would be:

.... | uniq -c | awk '{print $1}'

... which tells awk to split the line on whitespace then print the first field.

See Delete the numbers command "uniq -c" created for the corollary to your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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