如何计算文件(bash)中每一行中元素的出现次数
我有一个文件如下所示:如何计算文件(bash)中每一行中元素的出现次数,bash,awk,grep,structure,subject,Bash,Awk,Grep,Structure,Subject,我有一个文件如下所示: 1|2|3|4 1|2|3|4 1|2|3 1|2 1|2|3|4 1|2|3|4 4 line(s) have 3 occurrence(s) of | 1 line(s) have 2 occurrence(s) of | 1 line(s) have 1 occurrence(s) of | 我想做的是计算|在每行中出现的次数,并打印如下消息: 1|2|3|4 1|2|3|4 1|2|3 1|2 1|2|3|4 1|2|3|4 4 line(s) have 3
1|2|3|4
1|2|3|4
1|2|3
1|2
1|2|3|4
1|2|3|4
4 line(s) have 3 occurrence(s) of |
1 line(s) have 2 occurrence(s) of |
1 line(s) have 1 occurrence(s) of |
我想做的是计算|
在每行中出现的次数,并打印如下消息:
1|2|3|4
1|2|3|4
1|2|3
1|2
1|2|3|4
1|2|3|4
4 line(s) have 3 occurrence(s) of |
1 line(s) have 2 occurrence(s) of |
1 line(s) have 1 occurrence(s) of |
我一直在使用这个代码
grep-o'|'filename | wc-l
,但是它计算了|
在整个文件中出现的次数,而不仅仅是在每一行中。我是bash的新手,所以我非常感谢您的帮助 您可以使用此awk
:
awk-F“|”{++fq[NF-1]}END{for(fq中的F)printf“%d行出现了%d个%s\n”,fq[F],F,FS}”文件
1行中有1次出现|
1行中有2次出现|
4行中有3次出现|
要使其更具可读性,请执行以下操作:
awk-F“|”{
++fq[NF-1]
}
结束{
对于(fq中的f)
printf“%d行中出现了%d个%s\n”,fq[f],f,FS
}"档案"
您还可以使用以下脚本:
1|2|3|4
1|2|3|4
1|2|3
1|2
1|2|3|4
1|2|3|4
4 line(s) have 3 occurrence(s) of |
1 line(s) have 2 occurrence(s) of |
1 line(s) have 1 occurrence(s) of |
#/bin/bash
#变数
file=“$1”
声明-a结果
#扫描
而IFS='|'读一行;做
n=$(${行[@]}-1))
结果[$n]=$(${results[$n]}+1))
您所展示的样品已完成,请尝试以下内容
awk '
{
count[gsub(/\|/,"&")]++
}
END{
for(i in count){
print count[i] " line(s) have "i " occurrence(s) of |"
}
}' Input_file
输出如下
1 line(s) have 1 occurrence(s) of |
1 line(s) have 2 occurrence(s) of |
4 line(s) have 3 occurrence(s) of |