Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unix - count of columns in file

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

like image 972
toop Avatar asked Dec 25 '11 11:12

toop


People also ask

How do I count the number of columns in a file in Unix?

Method 1: Using head + sed + wc Commands We will again pipe this output to the wc command which will count these comma characters plus the carriage (\n) character as the total number of columns. We have successfully determined the number of columns on our CSV file as 7.

How do I count columns in bash?

Use head -n 1 for lowest column count, tail -n 1 for highest column count. Rows: cat file | wc -l or wc -l < file for the UUOC crowd. Show activity on this post. Alternatively to count columns, count the separators between columns.

How do I find the number of fields in awk?

awk with NF (number of fields) variable. NF is a built-in variable of awk command which is used to count the total number of fields in each line of the input text.

How do I count the number of rows in a csv file in Unix?

To count the number of records (or rows) in several CSV files the wc can used in conjunction with pipes. In the following example there are five CSV files. The requirement is to find out the sum of records in all five files. This can be achieved by piping the output of the cat command to wc.


2 Answers

awk -F'|' '{print NF; exit}' stores.dat  

Just quit right after the first line.

like image 163
Mat Avatar answered Sep 22 '22 00:09

Mat


This is a workaround (for me: I don't use awk very often):

Display the first row of the file containing the data, replace all pipes with newlines and then count the lines:

$ head -1 stores.dat | tr '|' '\n' | wc -l 
like image 34
miku Avatar answered Sep 26 '22 00:09

miku