generating frequency table from file

后端 未结 6 2175
暗喜
暗喜 2021-01-31 07:51

Given an input file containing one single number per line, how could I get a count of how many times an item occurred in that file?

cat input.txt
1
2
1
3
1
0
         


        
6条回答
  •  忘掉有多难
    2021-01-31 08:35

    perl -lne '$h{$_}++; END{for $n (sort keys %h) {print "$n\t$h{$n}"}}' input.txt
    

    Loop over each line with -n
    Each $_ number increments hash %h
    Once the END of input.txt has been reached,
    sort {$a <=> $b} the hash numerically
    Print the number $n and the frequency $h{$n}

    Similar code which works on floating point:

    perl -lne '$h{int($_)}++; END{for $n (sort {$a <=> $b} keys %h) {print "$n\t$h{$n}"}}' float.txt
    

    float.txt

    1.732
    2.236
    1.442
    3.162
    1.260
    0.707
    

    output:

    0       1
    1       3
    2       1
    3       1
    

提交回复
热议问题