Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Using hash table to count specific strings, and out put a result with time it repeat.

File A

AAA
BBB
CCC
DDD
BBB
DDD
AAA
CCC
BBB
AAA
BBB
CCC
BBB

Result

AAA 3
BBB 5
CCC 3
DDD 2
share|improve this question

3 Answers 3

up vote 3 down vote accepted

Is this homework? If not, just use sort and uniq:

$ sort file | uniq -c
  3 AAA
  5 BBB
  3 CCC
  2 DDD

If you need to script it yourself for some reason, you could use Perl:

$ perl -lne '$k{$_}++; END{print "$_\t$k{$_}" for keys(%k)}'
CCC 3
BBB 5
DDD 2
AAA 3

If you really need to use a shell script, you could do (here bash or ksh syntax):

unset num;
typeset -A num; 
while IFS= read -r line; do 
  ((num[$line]++))
done < file
for line in "${!num[@]}"; do 
  printf '%s\t%s\n' "$line" "${num[$line]}"
done
share|improve this answer
    
No need for chomp with -l. –  Stéphane Chazelas Feb 5 at 16:31
    
@StephaneChazelas indeed, thanks. It was left over from a first version that did not use -l. And thanks for the edit, an improvement, as usual. –  terdon Feb 5 at 16:49
    
@terdon thanks for wonderful answer. a lots things to learn –  JOSS Feb 6 at 0:37

With awk:

awk  '{count[$1]++} END {for (string in count) { print string ":" count[string]}}' data

where data is the name of your file

share|improve this answer
    
thanks for this helpful answer –  JOSS Feb 6 at 0:39

Another possibility is

cat file | sort | uniq | wc -l
share|improve this answer
2  
wc -l counts total lines in the file, it does not count total occurrences of unique strings. –  casey Feb 5 at 16:26
    
true, now it should be a valid answer –  juampa Feb 5 at 17:15
    
not quite, cat file | sort | uniq | wc -l will tell you the number of unique strings in the file, not the number of occurrences of each unique string. Also, cat is useless in this context as you can begin the pipeline with sort file. The right answer is sort file | uniq -c which you can see in the A by terdon. –  casey Feb 5 at 17:16
    
'uniq | wc -l' is not as precise as 'uniq -c'. Might prefer that output. –  flickerfly Aug 25 at 16:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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