添加 bash 文件中相似行中的数字

Adding numbers present in similar-lines of file in bash

我有这样的文件:

[host]$ cat /tmp/data
Breakfast 1
Lunch 1
Dinner 1
Dinner 1
Dinner 1
Lunch 1
Lunch 1
Dinner 1

我想要这样的输出:

Breakfast 1
Lunch 3
Dinner 4

我如何使用命令行脚本来完成此操作 awk/sed?

执行以下命令后我得到:

[host]$ cat /tmp/data | sort | tr " " "\n"
Breakfast
1
Dinner
1
Dinner
1
Dinner
1
Dinner
1
Lunch
1
Lunch
1
Lunch
1

我现在对如何添加这些数字感到困惑。

awk '{a[]+=} END{for(i in a){print i, a[i]}}' /tmp/data
Dinner 4
Breakfast 1
Lunch 3

能否请您尝试以下操作,它会以与第一个字段相同的顺序输出 Input_file。

awk '!a[]++{b[++count]=} {c[]++} END{for(i=1;i<=count;i++){print b[i],c[b[i]]}}' Input_file

输出如下。

Breakfast 1
Lunch 3
Dinner 4

说明:现在也添加上面代码的说明。

awk '
!a[]++{                    ##Checking condition if current lines first field is having only 1 count in array a then do following.
  b[++count]=              ##Creating an array named b whose index is variable count whose value is increasing number by 1 and value is .
}
{
  c[]++                    ##Creating an array named c whose index is  with increment value by 1.
}
END{                         ##Starting END block of awk code here.
  for(i=1;i<=count;i++){     ##Starting a for loop from i=1 to till value of count here.
    print b[i],c[b[i]]       ##Printing value of array b whose index is variable i and printing value of array c whose index is value of array b.
  }
}'  Input_file               ##Mentioning Input_file name here.

由于每行输入的数字总是1,您可以忽略它:

$ sort file | uniq -c | awk '{print , }'
Breakfast 1
Dinner 4
Lunch 3

或按出现次数排序:

$ sort file | uniq -c | sort -n | awk '{print , }'
Breakfast 1
Lunch 3
Dinner 4