Probably the easiest way to count number of columns in CSV file using bash shell is simply count number of commas in a single row. In the following example the content of the file myfile.csv
is:
$ cat myfile.csv 1,2,3,4,5 a,b,c,d,e a,b,c,d,e
First get only the first row using head
command:
$ head -1 myfile.csv 1,2,3,4,5
Next use sed
to remove everything except commas:
$ head -1 myfile.csv | sed 's/[^,]//g' ,,,,
All what has left is to simply use wc
command to count number of characters.
$ head -1 myfile.csv | sed 's/[^,]//g' | wc -c 5
The file has 5 columns. In case you wonder why there are only 4 commas and wc -l
returned 5 characters it is because wc
also counted \n
the carriage return as an extra character.