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条回答
狗以群分
2楼-- · 2020-02-16 06:42

select any row in the file (in the example below, it's the 2nd row) and count the number of columns, where the delimiter is a space:

sed -n 2p text_file.dat | tr ' ' '\n' | wc -l
查看更多
Melony?
3楼-- · 2020-02-16 06:45

If you have python installed you could try:

python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \
    stores.dat
查看更多
可以哭但决不认输i
4楼-- · 2020-02-16 06:46

Unless you're using spaces in there, you should be able to use | wc -w on the first line.

wc is "Word Count", which simply counts the words in the input file. If you send only one line, it'll tell you the amount of columns.

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-02-16 06:48

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
查看更多
啃猪蹄的小仙女
6楼-- · 2020-02-16 06:48

You could try

cat FILE | awk '{print NF}'

查看更多
登录 后发表回答