Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

awk - How to count the occurrence of an element in each line in a file (bash)

I have a file that looks like this:

1|2|3|4
1|2|3|4
1|2|3
1|2
1|2|3|4
1|2|3|4

what I want to do is to count the frequency of times that | appears in each line and to print a message like this:

4 line(s) have 3 occurrence(s) of |
1 line(s) have 2 occurrence(s) of |
1 line(s) have 1 occurrence(s) of |

I've been using this code grep -o '|' filename | wc -l but it's counting the amount of times that | appears in the whole file and not only in each line. I am new at bash so I would really appreciate your help!

question from:https://stackoverflow.com/questions/65944868/how-to-count-the-occurrence-of-an-element-in-each-line-in-a-file-bash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may use this awk:

awk -F "|" '{++fq[NF-1]} END {for (f in fq) printf "%d line(s) have %d occurrence(s) of %s
", fq[f], f, FS}' 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 |

To make it more readable:

awk -F "|" '{
   ++fq[NF-1]
}
END {
for (f in fq)
   printf "%d line(s) have %d occurrence(s) of %s
", fq[f], f, FS
}' file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...