【问题标题】:Adding numbers present in similar-lines of file in bash在 bash 中添加类似文件行中的数字
【发布时间】:2019-05-03 04:46:30
【问题描述】:
我有这样的文件:
[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
我现在不知道如何添加这些数字。
【问题讨论】:
标签:
sorting
awk
scripting
uniq
【解决方案1】:
awk '{a[$1]+=$2} END{for(i in a){print i, a[i]}}' /tmp/data
Dinner 4
Breakfast 1
Lunch 3
【解决方案2】:
您能否尝试以下操作,它会按照 Input_file 中第一个字段的顺序为您提供输出。
awk '!a[$1]++{b[++count]=$1} {c[$1]++} END{for(i=1;i<=count;i++){print b[i],c[b[i]]}}' Input_file
输出如下。
Breakfast 1
Lunch 3
Dinner 4
说明:现在也添加上述代码的说明。
awk '
!a[$1]++{ ##Checking condition if current lines first field is having only 1 count in array a then do following.
b[++count]=$1 ##Creating an array named b whose index is variable count whose value is increasing number by 1 and value is $1.
}
{
c[$1]++ ##Creating an array named c whose index is $1 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.
【解决方案3】:
由于每行输入的数字总是1,你可以忽略它:
$ sort file | uniq -c | awk '{print $2, $1}'
Breakfast 1
Dinner 4
Lunch 3
或按出现次数排序:
$ sort file | uniq -c | sort -n | awk '{print $2, $1}'
Breakfast 1
Lunch 3
Dinner 4