Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How to count the frequency of an element in every line of a file with 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 a | appears in each line and to print a message like: all lines have this amount except for this one that has this other amount.

Desired output should be something like this:

The "|" element appears 3 times in each line except in line 3 and 4 where it appears 2 and 1 times 

I am new at bash so I would really appreciate your help!

question from:https://stackoverflow.com/questions/65940507/how-to-count-the-frequency-of-an-element-in-every-line-of-a-file-with-bash

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

1 Answer

0 votes
by (71.8m points)

using awk:

awk -F| '{ if (map[NF-1]!="") { map[NF-1]=map[NF-1]","NR } else { map[NF-1]=NR } } END { for (i in map) { printf  "lines %s have %s occurances of |
",map[i],i } }' file

Explanation:

awk -F| '{                                                         # Set the field delimiter to |
            if (map[NF-1]!="") { 
                map[NF-1]=map[NF-1]","NR                            # Create an array called map with the number of | occurrences (NF-1) as the index and line number (NR) as the value
            } 
            else { 
                map[NF-1]=NR                                         # We don't want to prefix a comma if this is the first entry in the array
            } 
            map1[NF-1]++
           } 
       END { 
             for (i in map) { 
                printf  "line(s) %s have %s occurrence(s) of |
",map[i],i # At the end, print the contents of the array in the format required.
             }
             for (i in map1) {
                printf "%s line(s) have %s occurrence(s) of |, ",map1[i],i
             }
            printf "
"
            }' file

Output:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...