计算列中的字符串总数

时间:2013-03-11 08:51:30

标签: python perl awk

我想计算多个文件中的唯一行:

f1.txt

2039-177 GRAPE
2039-177 GRAPE
2039-176 GRAPE
2039-176 GRAPE
234-450  APPLE

f2.txt

690-346 MANGO
690-346 MANGO
347-348 GRAPE
4350-350 MANGO

所需输出

Total no:of grapes  - 3
Total no:of mangoes - 2
Total no:of apples  - 1

2 个答案:

答案 0 :(得分:2)

Pure Perl:

$ perl -lane '$seen{$_}++ or ++$n{lc $F[1]};
  END{print "Total no:of ${_}s - $n{$_}"
        for sort { $n{$b} <=> $n{$a} } keys %n}' f1.txt f2.txt
Total no:of grapes - 3
Total no:of mangos - 2
Total no:of apples - 1

管道:

$ cat f1.txt f2.txt | uniq | \
  perl -lanE '++$n{lc$F[1]};END{say"Total no:of ${_}s - $n{$_}"for keys%n}' | \
  sort -nrk5
Total no:of grapes - 3
Total no:of mangos - 2
Total no:of apples - 1

答案 1 :(得分:0)

也许这样的事情? (未测试)。

此解决方案期望输入文件的名称作为命令行上的参数。

use strict;
use warnings;

use List::Utils 'max';

my %count;
$count{ (split)[1] }++ while <>;

my $len = 1 + max map length, keys %count;

for (keys %count) {
    printf "Total no:of %-*s - %d\n", $len, lc $_.'s', $count{$_};
}