Sorting 添加bash中类似文件行中的数字
我有这样的文件:Sorting 添加bash中类似文件行中的数字,sorting,awk,scripting,uniq,Sorting,Awk,Scripting,Uniq,我有这样的文件: [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
[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[$1]+=$2} END{for(i in a){print i, a[i]}}' /tmp/data
Dinner 4
Breakfast 1
Lunch 3
awk '!a[$1]++{b[++count]=$1} {c[$1]++} END{for(i=1;i<=count;i++){print b[i],c[b[i]]}}' Input_file
解释:现在也添加对上述代码的解释
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.
awk'
!如果当前行第一个字段在数组a中只有1个计数,则执行[$1]+{###检查条件,然后执行以下操作。
b[++count]=$1##创建一个名为b的数组,该数组的索引为变量count,其值为数字增加1,值为$1。
}
{
c[$1]++##创建一个名为c的数组,其索引为$1,增量为1。
}
END{###这里是awk代码的起始结束块。
对于(i=1;i,因为每个输入行上的数字总是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
看到你的个人资料,你知道你从来没有选择一个答案作为正确的一个,给它一个时间,并选择所有答案中的任何一个作为正确的一个看到这个网址也一次
$ sort file | uniq -c | sort -n | awk '{print $2, $1}'
Breakfast 1
Lunch 3
Dinner 4