tags:

views:

96

answers:

4

Hello all,

I would like to count the occurrence of all commas in a very large text file (its has comma delimited data). Size is 28mb. I thought of loading up the text file and doing something like this:

substr_count($text, ',');

Good idea? Will it work?

The overall task is to find out how many rows of data it has. When I count the number of commas, I will divide this by the number of columns which will give me the number of rows. If there is a better way of doing this, let me know!

Thanks all

EDIT

The below worked but is it efficient as the suggestions?

$lines = file('C:\wamp\CE.txt');

$number = 0;

foreach($lines as $line){

   $number = $number + substr_count($line, ',');

}

echo $number;
A: 

Good idea? Will it work?

Have you tried it? That should tell a lot.

Basically, since substr_count is an intrinsic that does exactly what you want, it will very probably offer optimal performance.

If you find performance to be too bad, you might need to load the file in pieces, though.

Konrad Rudolph
+4  A: 

CSV goes like this:

lines -> rows
commas -> columns

So you got it wrong on the rows. If you want to count the rows just iterate the file for newlines.

$file = "youfile.txt"; 
$lines = count(file($file)); 
echo "There are ".$lines." lines in ".$file;

Would work as an example...

Frankie
did you mean CSV ?
siukurnin
lol, yes... damm dyslexia! ;) corrected, thks!
Frankie
This actually gives number of lines and not number of ",", my text file must not have newlines!!
Abs
So are you saying that the result of the above code on your file is 1? Maybe what you have is a very big line with some commas separating values, but not a CSV file. Does that better describe the situation?
Frankie
No, your code is actually correct! Thanks!
Abs
+1  A: 

If your records are separated by new lines, you could do the following to get the number of rows:

  $file = "input.csv";
  $rows = count(file($file));
Andre Miller
A: 

Frankie is right in his answer. Hoever, I'd suggest reading the file with the file() function and then simply counting the array elements.

Franz
How is that any different from Frankie’s answer?
Konrad Rudolph
Erm.. that is his answer
RMcLeod
Well, when I wrote it, he hadn't added the call to file() yet.
Franz