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
312 views
in Technique[技术] by (71.8m points)

Print 3x repetitions in second column in awk

I want to print the whole line, when my program finds in the second column exactly 3x repetition. How to do that?

This is the input

DGD1 SOL401
DGD2 SOL4717
DGD2 SOL4847
DGD3 SOL401
DGD3 SOL4991
DGD3 SOL329
DGD4 SOL4991
DGD5 SOL4717
DGD5 SOL4717
DGD5 SOL401

This is the expected output

DGD1 SOL401
DGD2 SOL4717
DGD3 SOL401
DGD5 SOL4717
DGD5 SOL4717
DGD5 SOL401
question from:https://stackoverflow.com/questions/65860690/print-3x-repetitions-in-second-column-in-awk

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

1 Reply

0 votes
by (71.8m points)

You don't need to read the input file twice:

awk '
    { vals[$2] = vals[$2] $0 ORS }
    END {
        for (i in vals) {
            if ( gsub(ORS,"&",vals[i]) == 3 ) {
                printf "%s", vals[i]
            }
        }
    }
' eq9_1.ndx

Note that the above will work even for input coming from a stream.


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

...