How to get CSV dimensions from terminal
Asked Answered
B

2

8

Suppose I'm in a folder where ls returns Test.csv. What command do I enter to get the number of rows and columns of Test.csv (a standard comma separated file)?

Breadwinner answered 2/11, 2013 at 10:4 Comment(1)
There is not such "command", the task is non-trivial. You have to implement some script for this.Adiel
C
26

Try using awk. It's best suited for well formatted csv file manipulations.

awk -F, 'END {printf "Number of Rows : %s\nNumber of Columns = %s\n", NR, NF}' Test.csv

-F, specifies , as a field separator in csv file.

At the end of file traversal, NR and NF have values of number of rows and columns respectively


Another quick and dirty approach would be like

# Number of Rows
cat Test.csv | wc -l

# Number of Columns
head -1 Test.csv | sed 's/,/\t/g' | wc -w
Cowes answered 2/11, 2013 at 10:17 Comment(0)
A
0

Although not a native solution using GNU coreutils, it is worth mentioning (since this is one of the top google results for such question) that xsv puts at your disposal a command to list the headers of a csv file, whose count returns obviously the number of columns.

# count rows
xsv count <filename>

# count columns
xsv headers <filename> | wc -l

For big files this is orders of magnitude faster than native solutions with awk and sed.

Argonaut answered 7/3, 2022 at 15:28 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.