0

If I have a CSV file and I want to know the number of columns, I'll use the following command:

  head -1 CSVFile.csv | sed 's/,/\t/g' | wc -w

However, whenever each column has a column name with a space in it, the command doesn't work and gives me a nonsense figure.

What would be the way to edit this command such that it gives me the correct number of columns?

e.g. in my file I could have column name (t - ZK) or (e - 22)

For example my file could be (first 2 row);

 ZZ(v - 1),Tat(t - 1000)
 1.1240128401924,2929292929
user2763361
  • 3,789
  • 11
  • 45
  • 81

5 Answers5

0

Maybe use the last line instead of the first. Change "head" to "tail". That would be a quick, easy solution.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
0

You are piping the sed output to wc -w which would return the number of words in the output. So if a field header contains spaces, those would be considered as different words.

You can use awk:

head -1 CSVFile.csv | awk -F, '{print NF}'

This would return the number of columns in the file (assuming the file is comma-delimited).

devnull
  • 118,548
  • 33
  • 236
  • 227
0

Try using awk

awk -F, 'NR==1 {print NF; exit}' CSVFile.csv

If you wish to use chain of head, sed and wc

Try using sed replace deliminator as newline \n instead of tab \t and then count number of lines using wc -l instead of counting number of words with wc -w

head -1 CSVFile.csv | sed 's/,/\n/g' | wc -l
jkshah
  • 11,387
  • 6
  • 35
  • 45
0
perl -ane 'print scalar(@F)-1 if($.==1)' your_file
Vijay
  • 65,327
  • 90
  • 227
  • 319
0

Assuming there is no "," in header name (like field1,"Surname,name",field3, ...)

sed "1 s/[^,]//g;q" CSVFile.csv | wc -c

Could also be made only in sed but a bit heavy for counting.

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43