unix - count of columns in file

前端 未结 11 1815
北海茫月
北海茫月 2020-12-22 19:17

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

相关标签:
11条回答
  • 2020-12-22 19:34

    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
    
    0 讨论(0)
  • 2020-12-22 19:40

    You could try

    cat FILE | awk '{print NF}'

    0 讨论(0)
  • 2020-12-22 19:41

    If you have python installed you could try:

    python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \
        stores.dat
    
    0 讨论(0)
  • 2020-12-22 19:42

    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.

    0 讨论(0)
  • 2020-12-22 19:42

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

    head -n 1 file.name | awk -F'|' '{print NF; exit}'
    
    0 讨论(0)
  • 2020-12-22 19: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
    
    0 讨论(0)
提交回复
热议问题