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.
FIND LATEST LINUX JOBS on LinuxCareers.com
Submit your RESUME, create a JOB ALERT or subscribe to RSS feed.
LINUX CAREER NEWSLETTER
Subscribe to NEWSLETTER and receive latest news, jobs, career advice and tutorials.
DO YOU NEED ADDITIONAL HELP?
Get extra help by visiting our LINUX FORUM or simply use comments below.

You may also be interested in:



Comments and Discussions