Unix Command to get the count of lines in a csv file

89,942

Solution 1

The following query helps you to get the count

cat FILE_NAME  | wc -l

Solution 2

All of the answers are wrong. CSV files accept line breaks in between quotes which should still be considered part of the same line. If you have either Python or PHP on your machine, you could be doing something like this:

Python

//From stdin
cat *.csv | python -c "import csv; import sys; print(sum(1 for i in csv.reader(sys.stdin)))"

//From file name
python -c "import csv; print(sum(1 for i in csv.reader(open('csv.csv'))))"

PHP

//From stdin
cat *.csv | php -r 'for($i=0; fgetcsv(STDIN); $i++);echo "$i\n";'

//From file name
php -r 'for($i=0, $fp=fopen("csv.csv", "r"); fgetcsv($fp); $i++);echo "$i\n";'

I have also created a script to simulate the output of wc -l: https://github.com/dhulke/CSVCount

Solution 3

In case you have multiple .csv files in the same folder, use

cat *.csv | wc -l

to get the total number of lines in all csv files in the current directory. So, -c counts characters and -m counts bytes (identical as long as you use ASCII). You can also use wc to count the number of files, e.g. by: ls -l | wc -l

Solution 4

wc -l mytextfile

Or to only output the number of lines:

wc -l < mytextfile

Usage: wc [OPTION]... [FILE]...
or:  wc [OPTION]... --files0-from=F
Print newline, word, and byte counts for each FILE, and a total line if
more than one FILE is specified.  With no FILE, or when FILE is -,
read standard input.
  -c, --bytes            print the byte counts
  -m, --chars            print the character counts
  -l, --lines            print the newline counts
  --files0-from=F    read input from the files specified by
                       NUL-terminated names in file F;
                       If F is - then read names from standard input
  -L, --max-line-length  print the length of the longest line
  -w, --words            print the word counts
  --help     display this help and exit
  --version  output version information and exit
Share:
89,942
Devoloper250
Author by

Devoloper250

Updated on September 29, 2021

Comments

  • Devoloper250
    Devoloper250 over 2 years

    Hi I am new to UNIX and I have to get the count of lines from incoming csv files. I have used the following command to get the count.

    wc -l filename.csv
    

    Consider files coming with 1 record iam getting some files with * at the start and for those files if i issue the same command iam getting count as 0. Does * mean anything in here and if i get a file with ctrlm(CR) instead of NL how to get the count of lines in that file. gimme a command that solves the issue. Thanks in advance.