unix - count of columns in file

toop picture toop · Dec 25, 2011 · Viewed 183.4k times · Source

Given a file with data like this (i.e. stores.dat file)

sid|storeNo|latitude|longitude
2|1|-28.03720000|153.42921670
9|2|-33.85090000|151.03274200

What would be a command to output the number of column names?

i.e. In the example above it would be 4. (number of pipe characters + 1 in the first line)

I was thinking something like:

awk '{ FS = "|" } ; { print NF}' stores.dat

but it returns all lines instead of just the first and for the first line it returns 1 instead of 4

Answer

Mat picture Mat · Dec 25, 2011
awk -F'|' '{print NF; exit}' stores.dat 

Just quit right after the first line.