0

I have a text file with hundreds of three digit numbers.
For example:

 0  2  3
 0  2  3
 0  2  9
 0  3  9
 0  9  2
 0  9  2
 0  9  9
 1  2  2
 1  2  2
 1  2  2
 1  2  9
 1  2  9
 1  3  3
 1  9  2
 1  9  2
 1  9  2
 1  9  3
 1  9  9
 1  9  9
 1  9  9
 1  9  9
 2  0  2
 2  0  3
 2  0  9
 2  1  2
 2  1  2
 2  1  3
 2  1  9
 2  1  9
 2  2  4
 2  2  5
 2  2  5
 2  2  5
 2  2  6
 2  2  6
 2  2  8

I want to convert this to show how many of each number is in the file to look something like this:

 0  2  3     2
 0  9  2     2
 1  2  2     3
 etc
  • the number do not display the right way after I posted the question. Sorry – Moe Shii Feb 13 at 1:14
  • Are those numbers all composed of single digits? If so, you can create a linear array of 1000 and use the numbers as indices to count their occurrences. – zx485 Feb 13 at 1:37
1

sort -n numbers.txt | uniq -c | sed -E 's/^( *[0-9]+) (.*)$/\2 \1/' would be the simplest way to achieve your goal. It:

  • sorts your numbers first, just in case
  • counts the length of each unique set
  • seds the result to move the count to the rear of each string
1

The fact that the lines consist of sequences of digits is largely irrelevant - unless you want to do arithmetic on the numbers themselves you can count / uniquify them just like any other strings e.g. using an associative array or hash:

awk '{c[$0]++} END {for (i in c) printf "%s\t%d\n", i, c[i]}' numbers.txt

or

perl -lnE '$c{$_}++ }{ for $k (keys %c) { say "$k\t$c{$k}" }' numbers.txt

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.