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

How to print filename with processed data in awk?

I am trying to print the filename with processed data but not getting desired output. In below example I am trying to find the record which is more than 100 and putting it in a counter and then add it in an array of filename so that I can print the number of record of greater than 100 with filename.

$awk -f test.awk f*
1 f1
4 f2
$cat test.awk
BEGIN{FS=","}
FNR==1 {filename=FILENAME; next}
{
    if(NF == 3 && $3 > 100) {
        counter++
    }
    a[filename]=counter
}
END{
    for(k in a){
        print  a[k], k
    }
}
$head f?
==> f1 <==
1,2,99
1,3,101
1,1,1
a,11,3,4
a,12,321,110

==> f2 <==
1,2,99
1,3,101
1,4,101
b,1,24,3
1,5,101
c,1,101,1
b,2,24,310
1,1,1

Expected output was -

1 f1
3 f2

Any suggestion?

question from:https://stackoverflow.com/questions/65851060/how-to-print-filename-with-processed-data-in-awk

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

1 Answer

0 votes
by (71.8m points)

Could you please try following, written and tested shown samples in GNU awk.

awk '
BEGIN{
  FS=","
}
FNR==1{
  if(count){
    print count,prevFilename
  }
  count=""
  prevFilename=FILENAME
}
$NF>100{
  ++count
}
END{
  if(count){
    print count,prevFilename
  }
}
' file1 file2

With shown samples output will be as follows.

1 file1
3 file2

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

...