ksp
ksp

Reputation: 25

Counting number of fields in unix

I am counting the number of fields in a row and spit out the row if the number of fields are more than the expected number of fields as below

awk -F”,” ‘{ if ( NF != ‘${x}’ ) print}’ filename

Where x is the expected number of fields. But this is throwing error if the file has more than 100 fields. What is the alternative approach for this.

Sample data:

1,aaaa,bbbb
2,aaaa,bbbb,cccc
3,aaaa,bbbb

Expected output

The line which has more than 3 fields should be displayed

2,aaaa,bbbb,cccc

The main issue here is my file has more than 100 columns and awk is throwing error as it has 100 fields limitation.

Upvotes: 0

Views: 189

Answers (1)

karakfa
karakfa

Reputation: 67467

$ x=3; awk -F, -v c="$x" 'NF!=c' file

2,aaaa,bbbb,cccc

if your awk has number of field limitation, here is a detour

$ grep -on , file | 
  awk -F: -v c="$x" '{a[$1]++} END{for(k in a) if(a[k]!=c) print k}' | 
  awk 'NR==FNR{a[$0]; next} FNR in a' - file

2,aaaa,bbbb,cccc

the two awk scripts don't parse the large file and should not depend number of fields limitation.

Upvotes: 1

Related Questions