计数和总和编号 文件中每个唯一行的出现次数

Sim*_*mdr 6 uniq

我认为这个问题的答案可能是该uniq函数的某种变体,它允许您计算每行在文件中出现的次数:

sort file.txt | uniq -c
Run Code Online (Sandbox Code Playgroud)

我的问题是我使用这个uniq函数来生成行数,并且因为我正在将输出与其他文件合并,我最终在文件中得到了需要进一步合理化的重复行。

例如,uniq在每行开头使用原始行数:

34 banana

23 apple

48 grapefruit

23 banana

12 apple
Run Code Online (Sandbox Code Playgroud)

所以我需要的是:

57 banana

35 apple

48 grapefruit
Run Code Online (Sandbox Code Playgroud)

SUM在其余字段相同的所有情况下,是否有一些函数可以在第一个字段上使用?

cha*_*aos 9

一个awk解决方案:

$ awk '{i[$2]+=$1} END{for(x in i){print i[x]" "x}}' file.txt
35 apple
48 grapefruit
57 banana
Run Code Online (Sandbox Code Playgroud)

首先awk创建一个数组,其索引为名称(香蕉、苹果、葡萄柚),并将第一列中的值相加。最后打印该数组。


Sob*_*que 1

我会用perl。

#!/usr/bin/perl

use strict; 
use warnings;

my %count_of;

while ( <> ) {
   my ( $word) = m/(\w+)/;
   $count_of{$word}++;
}

foreach my $word ( sort { $count_of{$a} <=> $count_of{$b} } keys %count_of ) {
    print "$count_of{$word} $word\n";
}
Run Code Online (Sandbox Code Playgroud)

运行它perl script.pl file1 file2 file3 file4

或者 - 你可能只想使用 cat.

cat file1 file2 file3 | sort | uniq -c
Run Code Online (Sandbox Code Playgroud)