How to Count Number of Columns in CSV File in Bash
You can use the awk
command to count the number of columns in a CSV file as shown below,
awk -F ',' '{print NF; exit}' file.csv
In above command, the -F
parameter sets the field separator to a comma. The NF
is a predefined variable which counts
the number of field in current row. The exit
avoid processing the entire file. Briefly, it prints number of fields and
exit.
Let’s take an example of file.csv
to count the number of columns in a CSV file.
The content of the file.csv
is as below
Id,W1,W2,C3,C4,C5
P1,41,50,6,8,10
P2,14,4,6,16,19
P3,16,17,9,10,12
P4,5,7,8,10,12
P5,15,6,11,8,10
Ther are 6 columns in file.csv
. Let’s count it with awk
,
awk -F ',' '{print NF; exit}' file.csv
Output:
6
This work is licensed under a Creative Commons Attribution 4.0 International License
Some of the links on this page may be affiliate links, which means we may get an affiliate commission on a valid purchase. The retailer will pay the commission at no additional cost to you.