SkyWalker
SkyWalker

Reputation: 14307

How to count the number of columns in the header of a csv file?

I need to count the number of header columns in a CSV file e.g.

A file called test.csv

a,b,c,d 
1,1,1,1
2,2,2,2
.......
n,n,n,n

should give me 4 columns. If I do:

awk -F, '{print NF}' ./test.csv

I will get 4 but n times i.e. I will get the number of columns for as many rows as there are and it is not really efficient. I tried this alternative form but doesn't work because it needs an input file:

awk -F, '{print NF}' `head -n 1 ./test.csv`

I could use this alternative but I find it ugly having to create a tmp file:

head -n 1 ./test.csv > tmp && awk -F, '{print NF}' tmp && rm tmp

Is there a simpler way?

Upvotes: 3

Views: 5585

Answers (3)

Etan Reisner
Etan Reisner

Reputation: 81002

Just print NF and exit.

awk -F, '{print NF; exit}' file.csv

It should be pointed out that this is not safe for arbitrary csv as csv can quote commas within elements and awk will not handle that correctly.

Upvotes: 9

Buggabill
Buggabill

Reputation: 13901

You can use head for this. Just flip what you have around, and pipe it to awk.

head -n 1 test.csv | awk -F, '{print NF}'

Upvotes: 2

fredtantini
fredtantini

Reputation: 16566

If you are sure that you have always the same number of columns, print NF only for the first line:

awk -F, 'NR==1{print NF}' ./test.csv

You could also use head without temporary files:

awk -F, '{print NF}' <(head -1 f)
head -1 f |awk -F, '{print NF}'

Upvotes: 2

Related Questions