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,5Next 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 5The 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.