B. Monster B. Monster - 6 months ago 10
Perl Question

Perl script to count number of each occurrence in a column

I want to count the amount of times each line occurs in a file

Given a column of info like

cat woman and bain
bat man
hat woman
cat man
bat man and friends
fat man
hat woman
+bat man
cat woman and bain
super bat man
bat man
bat man


I want to receive something like

2 cat woman and bain
3 bat man
2 hat woman
1 cat man
1 bat man and friends
1 fat man
1 +bat man
1 super bat man


I kind of have some unfinished code like

open OUTFILE, '>text.txt';
while (<>){
if( text.txt =~ $_ ){
#increment the count for this occurence
}else{
print OUTFILE $_;
}
}

Answer
$ sort file | uniq -c
      1 +bat man
      3 bat man
      1 bat man and friends
      1 cat man
      2 cat woman and bain
      1 fat man
      2 hat woman
      1 super bat man

or

$ perl -e'
   ++$h{$_} while <>;
   printf "%7d %s", $h{$_}, $_ for sort keys(%h);
' file
      1 +bat man
      3 bat man
      1 bat man and friends
      1 cat man
      2 cat woman and bain
      1 fat man
      2 hat woman
      1 super bat man

Replace sort with sort { $h{$b} <=> $h{$a} || $a cmp $b } to sort the output be descending count.