unix - count of columns in file

2020-02-16 06:20发布

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

11条回答
倾城 Initia
2楼-- · 2020-02-16 06:28

Proper pure way

Under bash, you could simply:

IFS=\| read -ra headline <stores.dat
echo ${#headline[@]}
4

A lot quicker as without forks, and reusable as $headline hold the full head line. You could, for sample:

printf " - %s\n" "${headline[@]}"
 - sid
 - storeNo
 - latitude
 - longitude

Nota This syntax will drive correctly spaces and others characters in column names.

Alternative: strong binary checking for max columns on each rows

What if some row do contain some extra columns?

This command will search for bigger line, counting separators:

tr -dc $'\n|' <stores.dat |wc -L
3

There are max 3 separators, then 4 fields.

查看更多
地球回转人心会变
3楼-- · 2020-02-16 06:33

This is usually what I use for counting the number of fields:

head -n 1 file.name | awk -F'|' '{print NF; exit}'
查看更多
祖国的老花朵
4楼-- · 2020-02-16 06:35

Perl solution similar to Mat's awk solution:

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

I've tested this on a file with 1000000 columns.


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

perl -lane 'print $#F+1; exit' stores.dat
查看更多
家丑人穷心不美
5楼-- · 2020-02-16 06:35

Based on Cat Kerr response. This command is working on solaris

awk '{print NF; exit}' stores.dat
查看更多
够拽才男人
6楼-- · 2020-02-16 06:36

you may try:

head -1 stores.dat | grep -o \|  | wc -l
查看更多
爷、活的狠高调
7楼-- · 2020-02-16 06:39
awk -F'|' '{print NF; exit}' stores.dat 

Just quit right after the first line.

查看更多
登录 后发表回答