1

I have a file that lists 5 lines of random words "See spot" "See pot run", etc each on a new line. I was able to create code that counted the number of times each word appears in the file and sorted properly.

4 Spot  
3 run  
2 see  
1 sees  
1 Run  
1 Jane  

Code I used:

cat "FILENAME" | tr ' ' '\n' | sort -n | uniq -c | sort -r  

I put each word on a new line, sorted, then counted unique values and sorted again. Now I have to take that count but with this output:

3 1  
1 2  
1 3  
1 4  

This means there are 3 words with a count of 1, 1 word 2, 1 word 3, 1 word 4.

I am having 2 problems. 1 is how can I get a count of the first column which is already a count from uniq -c. The second problem is deleting the words in the second column and replacing with the original count of 1, 2 ,3, 4.

2

You could do with something like:

tr ' ' '\n' <infile \
 | sort -n \
 | uniq -c \
 | awk '{ seen[$1]++ } END{for (x in seen) print seen[x], x }'

Or even:

tr ' ' '\n' <infile | sort -n | uniq -c|cut -d' ' -f7 |sort |uniq -c

Or better possible to do with awk alone:

awk '{ seen[$0]++ } 
    END{ for (x in seen) count[seen[x]]++; for (y in count) print count[y],y }
' RS='( |\n)+' infile
3 1
1 2
1 3
1 4

In above awk, in seen[$0]++ for each Record, Separated with either Space or a \newline stores the whole record into the associated array called seen as the key and its value increment when same key seen again.

At the END{ ... } when all records read, this block will be executed and for each key (we define x as variable index to travers all elements in that array using for loop) saved in array seen we used value of seen seen[x] as the key of new array called count and again its value increment for the same key.

Later we used another loop and y as variable index to print first they values count[y] (which are counts) and y they keys.

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.