VIPIN KUMAR
VIPIN KUMAR

Reputation: 3137

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?

Upvotes: 0

Views: 79

Answers (4)

Ed Morton
Ed Morton

Reputation: 203522

With GNU awk for ENDFILE:

$ awk -F, '(NF==3) && ($3>100){c++} ENDFILE{print c+0, FILENAME; c=0}' f1 f2
1 f1
3 f2

Upvotes: 0

Luuk
Luuk

Reputation: 14929

Add a debugging line to your code:

BEGIN{FS=","}
FNR==1 {filename=FILENAME; next}
{
    if(NF == 3 && $3 > 100) {
        counter++
        print "COUNTER:", counter, FILENAME, $0    # debugging
    }
    a[filename]=counter
}
END{
    for(k in a){
        print  a[k], k
    }
}

and examine the results:

COUNTER: 1 f1 1,3,101
COUNTER: 2 f2 1,3,101
COUNTER: 3 f2 1,4,101
COUNTER: 4 f2 1,5,101
1 f1
4 f2

What, do you think, is the output of 1 + 3......?

Upvotes: 0

anubhava
anubhava

Reputation: 785156

Using gnu-awk it can be simplified to:

awk -F, '$3 > 100 {++c} ENDFILE {print c, FILENAME; c=0}' f1 f2

1 f1
3 f2

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133518

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

Upvotes: 1

Related Questions