Search code examples
unixcutuniq

what is the alternate way to count the occurrence of each word without using 'uniq -c' command?


Is it possible to count the occurrence of each word like using uniq -c but with the count after the word rather than before?

Example scenario

Input file named as text1.txt which contain the following data

Renault:cilo:84563
Renault:cilo:84565
M&M:Thar:84566
Tata:nano:84567
M&M:quanto:84568
M&M:quanto:84569

The fields used in the above data are car_company:car_model:customerID

Desired result

cilo   2
Thar   1
nano   1
quanto 2

(car_model and number of cars sold grouped by car_model)

My code

cat test1.txt | cut -d: -f2 | uniq -c

Actual Result

   2 cilo   
   1 Thar   
   1 nano   
   2 quanto 

Is it possible to do the above process without using uniq -c ,so that I can swap the order of the fields (columns)?


Solution

  • You can use uniq, and simply post-process its output to swap the columns:

    cut -d: -f2 test1.txt | uniq -c | awk '{print $2 "\t" $1 "\n" }'
    

    EDIT: Added \n, as noted in a comment.