Unix - the number of columns in the file

For a file with data similar to this (i.e. store.dat file)

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

What will be the command to output the number of column names?

i.e. In the above example, this will be 4. (the number of channel characters + 1 in the first line)

I thought something like:

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

but it returns all rows instead of the first, and for the first row it returns 1 instead of 4

+47
linux scripting unix bash shell
Dec 25 2018-11-11T00:
source share
10 answers
 awk -F'|' '{print NF; exit}' stores.dat 

Just close right after the first line.

+72
Dec 25 '11 at 11:14
source share

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

Display the first line of the file containing the data, replace all channels with new lines, and then count the lines:

 $ head -1 stores.dat | tr '|' '\n' | wc -l 
+27
Dec 25 '11 at 11:13
source share

If you do not use spaces, you should use | wc -w | wc -w on the first line.

wc is a "Word Count" that simply counts the words in the input file. If you send only one row, it will tell you the number of columns.

+7
Dec 25 '11 at 11:11
source share

You can try

cat FILE | awk '{print NF}'

+4
Oct 23 '13 at 9:43 on
source share

If you have python installed, you can try:

 python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \ stores.dat 
+1
Dec 25 '11 at 11:16
source share

This is usually used to count the number of fields:

 head -n 1 file.name | awk -F'|' '{print NF; exit}' 
+1
Sep 11 '13 at 21:33
source share

Perl's solution is similar to Mat awk's:

 perl -F'\|' -lane 'print $#F+1; exit' stores.dat 

I tested this in a file with 1,000,000 columns.




If the field separator is a space (one or more spaces or tabs) instead of a channel:

 perl -lane 'print $#F+1; exit' stores.dat 
+1
Sep 10 '15 at 19:24
source share

Based on Cat Kerr answer. This team is working on solaris

 awk '{print NF; exit}' stores.dat 
0
Feb 23 '16 at 15:43
source share

you can try:

 head -1 stores.dat | grep -o \| | wc -l 
0
Nov 30 '16 at 13:36
source share

select any line in the file (in the example below, this is the second line) and count the number of columns where the separator is a space:

 sed -n 2p text_file.dat | tr ' ' '\n' | wc -l 
0
Oct 04 '17 at 16:05
source share



All Articles